blob: 8d4fea8ede15daacf989356f4b8ef461cb90d056 [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 Stinnerf2ea71f2011-12-17 04:13:41 +01003398PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003399PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
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 Stinnerf6a271a2014-08-01 12:28:48 +02003426 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 if (str == NULL) {
3428 if (error_pos == (size_t)-1) {
3429 PyErr_NoMemory();
3430 PyMem_Free(wstr);
3431 return NULL;
3432 }
3433 else {
3434 goto encode_error;
3435 }
3436 }
3437 PyMem_Free(wstr);
3438
3439 bytes = PyBytes_FromString(str);
3440 PyMem_Free(str);
3441 }
3442 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003443 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003444 size_t len, len2;
3445
3446 len = wcstombs(NULL, wstr, 0);
3447 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003448 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003449 goto encode_error;
3450 }
3451
3452 bytes = PyBytes_FromStringAndSize(NULL, len);
3453 if (bytes == NULL) {
3454 PyMem_Free(wstr);
3455 return NULL;
3456 }
3457
3458 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3459 if (len2 == (size_t)-1 || len2 > len) {
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003460 Py_DECREF(bytes);
Victor Stinner2f197072011-12-17 07:08:30 +01003461 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003462 goto encode_error;
3463 }
3464 PyMem_Free(wstr);
3465 }
3466 return bytes;
3467
3468encode_error:
3469 errmsg = strerror(errno);
3470 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003471
3472 if (error_pos == (size_t)-1)
3473 error_pos = wcstombs_errorpos(wstr);
3474
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003475 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003476
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003477 wstr = Py_DecodeLocale(errmsg, &errlen);
3478 if (wstr != NULL) {
3479 reason = PyUnicode_FromWideChar(wstr, errlen);
3480 PyMem_RawFree(wstr);
3481 } else {
3482 errmsg = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003483 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003484
Victor Stinner2f197072011-12-17 07:08:30 +01003485 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003486 reason = PyUnicode_FromString(
3487 "wcstombs() encountered an unencodable "
3488 "wide character");
3489 if (reason == NULL)
3490 return NULL;
3491
3492 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3493 "locale", unicode,
3494 (Py_ssize_t)error_pos,
3495 (Py_ssize_t)(error_pos+1),
3496 reason);
3497 Py_DECREF(reason);
3498 if (exc != NULL) {
3499 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003500 Py_DECREF(exc);
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003501 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003502 return NULL;
3503}
3504
Victor Stinnerad158722010-10-27 00:25:46 +00003505PyObject *
3506PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003507{
Steve Dowercc16be82016-09-08 10:35:16 -07003508#if defined(__APPLE__)
3509 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003510#else
Victor Stinner793b5312011-04-27 00:24:21 +02003511 PyInterpreterState *interp = PyThreadState_GET()->interp;
3512 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3513 cannot use it to encode and decode filenames before it is loaded. Load
3514 the Python codec requires to encode at least its own filename. Use the C
3515 version of the locale codec until the codec registry is initialized and
3516 the Python codec is loaded.
3517
3518 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3519 cannot only rely on it: check also interp->fscodec_initialized for
3520 subinterpreters. */
3521 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003522 return PyUnicode_AsEncodedString(unicode,
3523 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003524 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003525 }
3526 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003527 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003528 }
Victor Stinnerad158722010-10-27 00:25:46 +00003529#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003530}
3531
Alexander Belopolsky40018472011-02-26 01:02:56 +00003532PyObject *
3533PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003534 const char *encoding,
3535 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003536{
3537 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003538 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003539
Guido van Rossumd57fd912000-03-10 22:53:23 +00003540 if (!PyUnicode_Check(unicode)) {
3541 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543 }
Fred Drakee4315f52000-05-09 19:53:39 +00003544
Victor Stinner942889a2016-09-05 15:40:10 -07003545 if (encoding == NULL) {
3546 return _PyUnicode_AsUTF8String(unicode, errors);
3547 }
3548
Fred Drakee4315f52000-05-09 19:53:39 +00003549 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003550 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3551 char *lower = buflower;
3552
3553 /* Fast paths */
3554 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3555 lower += 3;
3556 if (*lower == '_') {
3557 /* Match "utf8" and "utf_8" */
3558 lower++;
3559 }
3560
3561 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003562 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003563 }
3564 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3565 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3566 }
3567 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3568 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3569 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003570 }
Victor Stinner942889a2016-09-05 15:40:10 -07003571 else {
3572 if (strcmp(lower, "ascii") == 0
3573 || strcmp(lower, "us_ascii") == 0) {
3574 return _PyUnicode_AsASCIIString(unicode, errors);
3575 }
Steve Dowercc16be82016-09-08 10:35:16 -07003576#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003577 else if (strcmp(lower, "mbcs") == 0) {
3578 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3579 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003580#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003581 else if (strcmp(lower, "latin1") == 0 ||
3582 strcmp(lower, "latin_1") == 0 ||
3583 strcmp(lower, "iso_8859_1") == 0 ||
3584 strcmp(lower, "iso8859_1") == 0) {
3585 return _PyUnicode_AsLatin1String(unicode, errors);
3586 }
3587 }
Victor Stinner37296e82010-06-10 13:36:23 +00003588 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003589
3590 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003591 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003592 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003593 return NULL;
3594
3595 /* The normal path */
3596 if (PyBytes_Check(v))
3597 return v;
3598
3599 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003600 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003601 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003602 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003603
3604 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003605 "encoder %s returned bytearray instead of bytes; "
3606 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003607 encoding);
3608 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003609 Py_DECREF(v);
3610 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003611 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003612
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003613 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3614 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003615 Py_DECREF(v);
3616 return b;
3617 }
3618
3619 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003620 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3621 "use codecs.encode() to encode to arbitrary types",
3622 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003623 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003624 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003625 return NULL;
3626}
3627
Alexander Belopolsky40018472011-02-26 01:02:56 +00003628PyObject *
3629PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003630 const char *encoding,
3631 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003632{
3633 PyObject *v;
3634
3635 if (!PyUnicode_Check(unicode)) {
3636 PyErr_BadArgument();
3637 goto onError;
3638 }
3639
Serhiy Storchaka00939072016-10-27 21:05:49 +03003640 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3641 "PyUnicode_AsEncodedUnicode() is deprecated; "
3642 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3643 return NULL;
3644
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003645 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003646 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003647
3648 /* Encode via the codec registry */
3649 v = PyCodec_Encode(unicode, encoding, errors);
3650 if (v == NULL)
3651 goto onError;
3652 if (!PyUnicode_Check(v)) {
3653 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003654 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3655 "use codecs.encode() to encode to arbitrary types",
3656 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003657 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003658 Py_DECREF(v);
3659 goto onError;
3660 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003661 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003662
Benjamin Peterson29060642009-01-31 22:14:21 +00003663 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003664 return NULL;
3665}
3666
Victor Stinner2f197072011-12-17 07:08:30 +01003667static size_t
3668mbstowcs_errorpos(const char *str, size_t len)
3669{
3670#ifdef HAVE_MBRTOWC
3671 const char *start = str;
3672 mbstate_t mbs;
3673 size_t converted;
3674 wchar_t ch;
3675
3676 memset(&mbs, 0, sizeof mbs);
3677 while (len)
3678 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003679 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003680 if (converted == 0)
3681 /* Reached end of string */
3682 break;
3683 if (converted == (size_t)-1 || converted == (size_t)-2) {
3684 /* Conversion error or incomplete character */
3685 return str - start;
3686 }
3687 else {
3688 str += converted;
3689 len -= converted;
3690 }
3691 }
3692 /* failed to find the undecodable byte sequence */
3693 return 0;
3694#endif
3695 return 0;
3696}
3697
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003698PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003699PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003700 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003701{
3702 wchar_t smallbuf[256];
3703 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3704 wchar_t *wstr;
3705 size_t wlen, wlen2;
3706 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003707 int surrogateescape;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003708 size_t error_pos, errlen;
Victor Stinner2f197072011-12-17 07:08:30 +01003709 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003710 PyObject *exc, *reason = NULL; /* initialize to prevent gcc warning */
Victor Stinner1b579672011-12-17 05:47:23 +01003711
3712 if (locale_error_handler(errors, &surrogateescape) < 0)
3713 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003714
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003715 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3716 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003717 return NULL;
3718 }
3719
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003720 if (surrogateescape) {
3721 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003722 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003723 if (wstr == NULL) {
3724 if (wlen == (size_t)-1)
3725 PyErr_NoMemory();
3726 else
3727 PyErr_SetFromErrno(PyExc_OSError);
3728 return NULL;
3729 }
3730
3731 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003732 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003733 }
3734 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003735 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003736#ifndef HAVE_BROKEN_MBSTOWCS
3737 wlen = mbstowcs(NULL, str, 0);
3738#else
3739 wlen = len;
3740#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003741 if (wlen == (size_t)-1)
3742 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003743 if (wlen+1 <= smallbuf_len) {
3744 wstr = smallbuf;
3745 }
3746 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003747 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003748 if (!wstr)
3749 return PyErr_NoMemory();
3750 }
3751
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003752 wlen2 = mbstowcs(wstr, str, wlen+1);
3753 if (wlen2 == (size_t)-1) {
3754 if (wstr != smallbuf)
3755 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003756 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003757 }
3758#ifdef HAVE_BROKEN_MBSTOWCS
3759 assert(wlen2 == wlen);
3760#endif
3761 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3762 if (wstr != smallbuf)
3763 PyMem_Free(wstr);
3764 }
3765 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003766
3767decode_error:
3768 errmsg = strerror(errno);
3769 assert(errmsg != NULL);
3770
3771 error_pos = mbstowcs_errorpos(str, len);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003772 wstr = Py_DecodeLocale(errmsg, &errlen);
3773 if (wstr != NULL) {
3774 reason = PyUnicode_FromWideChar(wstr, errlen);
3775 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003776 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003777
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003778 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003779 reason = PyUnicode_FromString(
3780 "mbstowcs() encountered an invalid multibyte sequence");
3781 if (reason == NULL)
3782 return NULL;
3783
3784 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3785 "locale", str, len,
3786 (Py_ssize_t)error_pos,
3787 (Py_ssize_t)(error_pos+1),
3788 reason);
3789 Py_DECREF(reason);
3790 if (exc != NULL) {
3791 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003792 Py_DECREF(exc);
Victor Stinner2f197072011-12-17 07:08:30 +01003793 }
3794 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003795}
3796
3797PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003798PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003799{
3800 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003801 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003802}
3803
3804
3805PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003806PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003807 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003808 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3809}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003810
Christian Heimes5894ba72007-11-04 11:43:14 +00003811PyObject*
3812PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3813{
Steve Dowercc16be82016-09-08 10:35:16 -07003814#if defined(__APPLE__)
3815 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003816#else
Victor Stinner793b5312011-04-27 00:24:21 +02003817 PyInterpreterState *interp = PyThreadState_GET()->interp;
3818 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3819 cannot use it to encode and decode filenames before it is loaded. Load
3820 the Python codec requires to encode at least its own filename. Use the C
3821 version of the locale codec until the codec registry is initialized and
3822 the Python codec is loaded.
3823
3824 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3825 cannot only rely on it: check also interp->fscodec_initialized for
3826 subinterpreters. */
3827 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003828 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003829 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003830 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003831 }
3832 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003833 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003834 }
Victor Stinnerad158722010-10-27 00:25:46 +00003835#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003836}
3837
Martin v. Löwis011e8422009-05-05 04:43:17 +00003838
3839int
3840PyUnicode_FSConverter(PyObject* arg, void* addr)
3841{
Brett Cannonec6ce872016-09-06 15:50:29 -07003842 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003843 PyObject *output = NULL;
3844 Py_ssize_t size;
3845 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003846 if (arg == NULL) {
3847 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003848 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003849 return 1;
3850 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003851 path = PyOS_FSPath(arg);
3852 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003853 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003854 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003855 if (PyBytes_Check(path)) {
3856 output = path;
3857 }
3858 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3859 output = PyUnicode_EncodeFSDefault(path);
3860 Py_DECREF(path);
3861 if (!output) {
3862 return 0;
3863 }
3864 assert(PyBytes_Check(output));
3865 }
3866
Victor Stinner0ea2a462010-04-30 00:22:08 +00003867 size = PyBytes_GET_SIZE(output);
3868 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003869 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003870 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003871 Py_DECREF(output);
3872 return 0;
3873 }
3874 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003875 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003876}
3877
3878
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003879int
3880PyUnicode_FSDecoder(PyObject* arg, void* addr)
3881{
Brett Cannona5711202016-09-06 19:36:01 -07003882 int is_buffer = 0;
3883 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003884 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003885 if (arg == NULL) {
3886 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003887 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003888 return 1;
3889 }
Brett Cannona5711202016-09-06 19:36:01 -07003890
3891 is_buffer = PyObject_CheckBuffer(arg);
3892 if (!is_buffer) {
3893 path = PyOS_FSPath(arg);
3894 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003895 return 0;
3896 }
Brett Cannona5711202016-09-06 19:36:01 -07003897 }
3898 else {
3899 path = arg;
3900 Py_INCREF(arg);
3901 }
3902
3903 if (PyUnicode_Check(path)) {
3904 if (PyUnicode_READY(path) == -1) {
3905 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003906 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003907 }
3908 output = path;
3909 }
3910 else if (PyBytes_Check(path) || is_buffer) {
3911 PyObject *path_bytes = NULL;
3912
3913 if (!PyBytes_Check(path) &&
3914 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3915 "path should be string, bytes, or os.PathLike, not %.200s",
3916 Py_TYPE(arg)->tp_name)) {
3917 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003918 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003919 }
3920 path_bytes = PyBytes_FromObject(path);
3921 Py_DECREF(path);
3922 if (!path_bytes) {
3923 return 0;
3924 }
3925 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3926 PyBytes_GET_SIZE(path_bytes));
3927 Py_DECREF(path_bytes);
3928 if (!output) {
3929 return 0;
3930 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003931 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003932 else {
3933 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003934 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003935 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003936 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003937 return 0;
3938 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003939 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003940 Py_DECREF(output);
3941 return 0;
3942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003944 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003945 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003946 Py_DECREF(output);
3947 return 0;
3948 }
3949 *(PyObject**)addr = output;
3950 return Py_CLEANUP_SUPPORTED;
3951}
3952
3953
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003954const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003955PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003956{
Christian Heimesf3863112007-11-22 07:46:41 +00003957 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003958
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003959 if (!PyUnicode_Check(unicode)) {
3960 PyErr_BadArgument();
3961 return NULL;
3962 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003963 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003964 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003965
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003966 if (PyUnicode_UTF8(unicode) == NULL) {
3967 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003968 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003969 if (bytes == NULL)
3970 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003971 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3972 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003973 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 Py_DECREF(bytes);
3975 return NULL;
3976 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003977 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003978 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003979 PyBytes_AS_STRING(bytes),
3980 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981 Py_DECREF(bytes);
3982 }
3983
3984 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003985 *psize = PyUnicode_UTF8_LENGTH(unicode);
3986 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003987}
3988
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003989const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003990PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003991{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3993}
3994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003995Py_UNICODE *
3996PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3997{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 const unsigned char *one_byte;
3999#if SIZEOF_WCHAR_T == 4
4000 const Py_UCS2 *two_bytes;
4001#else
4002 const Py_UCS4 *four_bytes;
4003 const Py_UCS4 *ucs4_end;
4004 Py_ssize_t num_surrogates;
4005#endif
4006 wchar_t *w;
4007 wchar_t *wchar_end;
4008
4009 if (!PyUnicode_Check(unicode)) {
4010 PyErr_BadArgument();
4011 return NULL;
4012 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004013 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004014 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004015 assert(_PyUnicode_KIND(unicode) != 0);
4016 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004017
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004018 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004020 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4021 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022 num_surrogates = 0;
4023
4024 for (; four_bytes < ucs4_end; ++four_bytes) {
4025 if (*four_bytes > 0xFFFF)
4026 ++num_surrogates;
4027 }
4028
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004029 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4030 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4031 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004032 PyErr_NoMemory();
4033 return NULL;
4034 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004035 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004036
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004037 w = _PyUnicode_WSTR(unicode);
4038 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4039 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004040 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4041 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004042 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004043 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004044 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4045 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004046 }
4047 else
4048 *w = *four_bytes;
4049
4050 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07004051 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004052 }
4053 }
4054 *w = 0;
4055#else
4056 /* sizeof(wchar_t) == 4 */
4057 Py_FatalError("Impossible unicode object state, wstr and str "
4058 "should share memory already.");
4059 return NULL;
4060#endif
4061 }
4062 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004063 if ((size_t)_PyUnicode_LENGTH(unicode) >
4064 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4065 PyErr_NoMemory();
4066 return NULL;
4067 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004068 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4069 (_PyUnicode_LENGTH(unicode) + 1));
4070 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004071 PyErr_NoMemory();
4072 return NULL;
4073 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004074 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4075 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4076 w = _PyUnicode_WSTR(unicode);
4077 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004078
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004079 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4080 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004081 for (; w < wchar_end; ++one_byte, ++w)
4082 *w = *one_byte;
4083 /* null-terminate the wstr */
4084 *w = 0;
4085 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004086 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004088 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004089 for (; w < wchar_end; ++two_bytes, ++w)
4090 *w = *two_bytes;
4091 /* null-terminate the wstr */
4092 *w = 0;
4093#else
4094 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004095 PyObject_FREE(_PyUnicode_WSTR(unicode));
4096 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097 Py_FatalError("Impossible unicode object state, wstr "
4098 "and str should share memory already.");
4099 return NULL;
4100#endif
4101 }
4102 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07004103 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004104 }
4105 }
4106 }
4107 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004108 *size = PyUnicode_WSTR_LENGTH(unicode);
4109 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004110}
4111
Alexander Belopolsky40018472011-02-26 01:02:56 +00004112Py_UNICODE *
4113PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004114{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004115 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004116}
4117
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03004118const Py_UNICODE *
4119_PyUnicode_AsUnicode(PyObject *unicode)
4120{
4121 Py_ssize_t size;
4122 const Py_UNICODE *wstr;
4123
4124 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
4125 if (wstr && wcslen(wstr) != (size_t)size) {
4126 PyErr_SetString(PyExc_ValueError, "embedded null character");
4127 return NULL;
4128 }
4129 return wstr;
4130}
4131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004132
Alexander Belopolsky40018472011-02-26 01:02:56 +00004133Py_ssize_t
4134PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004135{
4136 if (!PyUnicode_Check(unicode)) {
4137 PyErr_BadArgument();
4138 goto onError;
4139 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004140 if (_PyUnicode_WSTR(unicode) == NULL) {
4141 if (PyUnicode_AsUnicode(unicode) == NULL)
4142 goto onError;
4143 }
4144 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004145
Benjamin Peterson29060642009-01-31 22:14:21 +00004146 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004147 return -1;
4148}
4149
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004150Py_ssize_t
4151PyUnicode_GetLength(PyObject *unicode)
4152{
Victor Stinner07621332012-06-16 04:53:46 +02004153 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004154 PyErr_BadArgument();
4155 return -1;
4156 }
Victor Stinner07621332012-06-16 04:53:46 +02004157 if (PyUnicode_READY(unicode) == -1)
4158 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004159 return PyUnicode_GET_LENGTH(unicode);
4160}
4161
4162Py_UCS4
4163PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4164{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004165 void *data;
4166 int kind;
4167
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004168 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004169 PyErr_BadArgument();
4170 return (Py_UCS4)-1;
4171 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004172 if (PyUnicode_READY(unicode) == -1) {
4173 return (Py_UCS4)-1;
4174 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004175 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004176 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004177 return (Py_UCS4)-1;
4178 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004179 data = PyUnicode_DATA(unicode);
4180 kind = PyUnicode_KIND(unicode);
4181 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004182}
4183
4184int
4185PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4186{
4187 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004188 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004189 return -1;
4190 }
Victor Stinner488fa492011-12-12 00:01:39 +01004191 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004192 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004193 PyErr_SetString(PyExc_IndexError, "string index out of range");
4194 return -1;
4195 }
Victor Stinner488fa492011-12-12 00:01:39 +01004196 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004197 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004198 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4199 PyErr_SetString(PyExc_ValueError, "character out of range");
4200 return -1;
4201 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004202 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4203 index, ch);
4204 return 0;
4205}
4206
Alexander Belopolsky40018472011-02-26 01:02:56 +00004207const char *
4208PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004209{
Victor Stinner42cb4622010-09-01 19:39:01 +00004210 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004211}
4212
Victor Stinner554f3f02010-06-16 23:33:54 +00004213/* create or adjust a UnicodeDecodeError */
4214static void
4215make_decode_exception(PyObject **exceptionObject,
4216 const char *encoding,
4217 const char *input, Py_ssize_t length,
4218 Py_ssize_t startpos, Py_ssize_t endpos,
4219 const char *reason)
4220{
4221 if (*exceptionObject == NULL) {
4222 *exceptionObject = PyUnicodeDecodeError_Create(
4223 encoding, input, length, startpos, endpos, reason);
4224 }
4225 else {
4226 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4227 goto onError;
4228 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4229 goto onError;
4230 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4231 goto onError;
4232 }
4233 return;
4234
4235onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004236 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004237}
4238
Steve Dowercc16be82016-09-08 10:35:16 -07004239#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004240/* error handling callback helper:
4241 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004242 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004243 and adjust various state variables.
4244 return 0 on success, -1 on error
4245*/
4246
Alexander Belopolsky40018472011-02-26 01:02:56 +00004247static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004248unicode_decode_call_errorhandler_wchar(
4249 const char *errors, PyObject **errorHandler,
4250 const char *encoding, const char *reason,
4251 const char **input, const char **inend, Py_ssize_t *startinpos,
4252 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4253 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004254{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004255 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004256
4257 PyObject *restuple = NULL;
4258 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004259 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004260 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004261 Py_ssize_t requiredsize;
4262 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004263 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004264 wchar_t *repwstr;
4265 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004267 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4268 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004269
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004270 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 *errorHandler = PyCodec_LookupError(errors);
4272 if (*errorHandler == NULL)
4273 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004274 }
4275
Victor Stinner554f3f02010-06-16 23:33:54 +00004276 make_decode_exception(exceptionObject,
4277 encoding,
4278 *input, *inend - *input,
4279 *startinpos, *endinpos,
4280 reason);
4281 if (*exceptionObject == NULL)
4282 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004283
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004284 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004285 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004286 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004287 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004288 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004289 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004290 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004291 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004292 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004293
4294 /* Copy back the bytes variables, which might have been modified by the
4295 callback */
4296 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4297 if (!inputobj)
4298 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004299 *input = PyBytes_AS_STRING(inputobj);
4300 insize = PyBytes_GET_SIZE(inputobj);
4301 *inend = *input + insize;
4302 /* we can DECREF safely, as the exception has another reference,
4303 so the object won't go away. */
4304 Py_DECREF(inputobj);
4305
4306 if (newpos<0)
4307 newpos = insize+newpos;
4308 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004309 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004310 goto onError;
4311 }
4312
4313 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4314 if (repwstr == NULL)
4315 goto onError;
4316 /* need more space? (at least enough for what we
4317 have+the replacement+the rest of the string (starting
4318 at the new input position), so we won't have to check space
4319 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004320 requiredsize = *outpos;
4321 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4322 goto overflow;
4323 requiredsize += repwlen;
4324 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4325 goto overflow;
4326 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004327 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004328 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004329 requiredsize = 2*outsize;
4330 if (unicode_resize(output, requiredsize) < 0)
4331 goto onError;
4332 }
4333 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4334 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004335 *endinpos = newpos;
4336 *inptr = *input + newpos;
4337
4338 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004339 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004340 return 0;
4341
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004342 overflow:
4343 PyErr_SetString(PyExc_OverflowError,
4344 "decoded result is too long for a Python string");
4345
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004346 onError:
4347 Py_XDECREF(restuple);
4348 return -1;
4349}
Steve Dowercc16be82016-09-08 10:35:16 -07004350#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004351
4352static int
4353unicode_decode_call_errorhandler_writer(
4354 const char *errors, PyObject **errorHandler,
4355 const char *encoding, const char *reason,
4356 const char **input, const char **inend, Py_ssize_t *startinpos,
4357 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4358 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4359{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004360 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004361
4362 PyObject *restuple = NULL;
4363 PyObject *repunicode = NULL;
4364 Py_ssize_t insize;
4365 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004366 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004367 PyObject *inputobj = NULL;
4368
4369 if (*errorHandler == NULL) {
4370 *errorHandler = PyCodec_LookupError(errors);
4371 if (*errorHandler == NULL)
4372 goto onError;
4373 }
4374
4375 make_decode_exception(exceptionObject,
4376 encoding,
4377 *input, *inend - *input,
4378 *startinpos, *endinpos,
4379 reason);
4380 if (*exceptionObject == NULL)
4381 goto onError;
4382
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004383 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004384 if (restuple == NULL)
4385 goto onError;
4386 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004387 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004388 goto onError;
4389 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004390 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004391 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004392
4393 /* Copy back the bytes variables, which might have been modified by the
4394 callback */
4395 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4396 if (!inputobj)
4397 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004398 *input = PyBytes_AS_STRING(inputobj);
4399 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004400 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004401 /* we can DECREF safely, as the exception has another reference,
4402 so the object won't go away. */
4403 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004405 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004406 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004407 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004408 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004409 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004410 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004411
Victor Stinner170ca6f2013-04-18 00:25:28 +02004412 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004413 if (replen > 1) {
4414 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004415 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004416 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4417 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4418 goto onError;
4419 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004421 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004422
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004423 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004424 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004425
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004426 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004427 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004428 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004429
Benjamin Peterson29060642009-01-31 22:14:21 +00004430 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004433}
4434
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435/* --- UTF-7 Codec -------------------------------------------------------- */
4436
Antoine Pitrou244651a2009-05-04 18:56:13 +00004437/* See RFC2152 for details. We encode conservatively and decode liberally. */
4438
4439/* Three simple macros defining base-64. */
4440
4441/* Is c a base-64 character? */
4442
4443#define IS_BASE64(c) \
4444 (((c) >= 'A' && (c) <= 'Z') || \
4445 ((c) >= 'a' && (c) <= 'z') || \
4446 ((c) >= '0' && (c) <= '9') || \
4447 (c) == '+' || (c) == '/')
4448
4449/* given that c is a base-64 character, what is its base-64 value? */
4450
4451#define FROM_BASE64(c) \
4452 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4453 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4454 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4455 (c) == '+' ? 62 : 63)
4456
4457/* What is the base-64 character of the bottom 6 bits of n? */
4458
4459#define TO_BASE64(n) \
4460 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4461
4462/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4463 * decoded as itself. We are permissive on decoding; the only ASCII
4464 * byte not decoding to itself is the + which begins a base64
4465 * string. */
4466
4467#define DECODE_DIRECT(c) \
4468 ((c) <= 127 && (c) != '+')
4469
4470/* The UTF-7 encoder treats ASCII characters differently according to
4471 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4472 * the above). See RFC2152. This array identifies these different
4473 * sets:
4474 * 0 : "Set D"
4475 * alphanumeric and '(),-./:?
4476 * 1 : "Set O"
4477 * !"#$%&*;<=>@[]^_`{|}
4478 * 2 : "whitespace"
4479 * ht nl cr sp
4480 * 3 : special (must be base64 encoded)
4481 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4482 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483
Tim Petersced69f82003-09-16 20:30:58 +00004484static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004485char utf7_category[128] = {
4486/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4487 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4488/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4489 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4490/* sp ! " # $ % & ' ( ) * + , - . / */
4491 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4492/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4493 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4494/* @ A B C D E F G H I J K L M N O */
4495 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4496/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4497 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4498/* ` a b c d e f g h i j k l m n o */
4499 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4500/* p q r s t u v w x y z { | } ~ del */
4501 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502};
4503
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504/* ENCODE_DIRECT: this character should be encoded as itself. The
4505 * answer depends on whether we are encoding set O as itself, and also
4506 * on whether we are encoding whitespace as itself. RFC2152 makes it
4507 * clear that the answers to these questions vary between
4508 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004509
Antoine Pitrou244651a2009-05-04 18:56:13 +00004510#define ENCODE_DIRECT(c, directO, directWS) \
4511 ((c) < 128 && (c) > 0 && \
4512 ((utf7_category[(c)] == 0) || \
4513 (directWS && (utf7_category[(c)] == 2)) || \
4514 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515
Alexander Belopolsky40018472011-02-26 01:02:56 +00004516PyObject *
4517PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004518 Py_ssize_t size,
4519 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004521 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4522}
4523
Antoine Pitrou244651a2009-05-04 18:56:13 +00004524/* The decoder. The only state we preserve is our read position,
4525 * i.e. how many characters we have consumed. So if we end in the
4526 * middle of a shift sequence we have to back off the read position
4527 * and the output to the beginning of the sequence, otherwise we lose
4528 * all the shift state (seen bits, number of bits seen, high
4529 * surrogate). */
4530
Alexander Belopolsky40018472011-02-26 01:02:56 +00004531PyObject *
4532PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004533 Py_ssize_t size,
4534 const char *errors,
4535 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004536{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004537 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004538 Py_ssize_t startinpos;
4539 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004541 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 const char *errmsg = "";
4543 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004544 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 unsigned int base64bits = 0;
4546 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004547 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004548 PyObject *errorHandler = NULL;
4549 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004551 if (size == 0) {
4552 if (consumed)
4553 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004554 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004555 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004557 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004558 _PyUnicodeWriter_Init(&writer);
4559 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004560
4561 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004562 e = s + size;
4563
4564 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004565 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004566 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004567 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004568
Antoine Pitrou244651a2009-05-04 18:56:13 +00004569 if (inShift) { /* in a base-64 section */
4570 if (IS_BASE64(ch)) { /* consume a base-64 character */
4571 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4572 base64bits += 6;
4573 s++;
4574 if (base64bits >= 16) {
4575 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004576 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 base64bits -= 16;
4578 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004579 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 if (surrogate) {
4581 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004582 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4583 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004584 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004585 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004587 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004588 }
4589 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004590 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004591 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004592 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 }
4594 }
Victor Stinner551ac952011-11-29 22:58:13 +01004595 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 /* first surrogate */
4597 surrogate = outCh;
4598 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004600 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004601 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 }
4603 }
4604 }
4605 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004606 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004607 if (base64bits > 0) { /* left-over bits */
4608 if (base64bits >= 6) {
4609 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004610 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004611 errmsg = "partial character in shift sequence";
4612 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004614 else {
4615 /* Some bits remain; they should be zero */
4616 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004617 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004618 errmsg = "non-zero padding bits in shift sequence";
4619 goto utf7Error;
4620 }
4621 }
4622 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004623 if (surrogate && DECODE_DIRECT(ch)) {
4624 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4625 goto onError;
4626 }
4627 surrogate = 0;
4628 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004629 /* '-' is absorbed; other terminating
4630 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004631 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004632 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004633 }
4634 }
4635 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004636 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004637 s++; /* consume '+' */
4638 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004639 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004640 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004641 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004642 }
4643 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004644 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004645 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004646 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004647 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004648 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004649 }
4650 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004651 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004652 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004653 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004654 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004655 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004656 else {
4657 startinpos = s-starts;
4658 s++;
4659 errmsg = "unexpected special character";
4660 goto utf7Error;
4661 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004662 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004663utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004664 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004665 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004666 errors, &errorHandler,
4667 "utf7", errmsg,
4668 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004669 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004670 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004671 }
4672
Antoine Pitrou244651a2009-05-04 18:56:13 +00004673 /* end of string */
4674
4675 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4676 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004677 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004678 if (surrogate ||
4679 (base64bits >= 6) ||
4680 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004681 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004682 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004683 errors, &errorHandler,
4684 "utf7", "unterminated shift sequence",
4685 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004686 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004687 goto onError;
4688 if (s < e)
4689 goto restart;
4690 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004691 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004692
4693 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004694 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004695 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004696 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004697 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004698 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004699 writer.kind, writer.data, shiftOutStart);
4700 Py_XDECREF(errorHandler);
4701 Py_XDECREF(exc);
4702 _PyUnicodeWriter_Dealloc(&writer);
4703 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004704 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004705 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004706 }
4707 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004708 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004709 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004710 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004711
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004712 Py_XDECREF(errorHandler);
4713 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004714 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004715
Benjamin Peterson29060642009-01-31 22:14:21 +00004716 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004717 Py_XDECREF(errorHandler);
4718 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004719 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004720 return NULL;
4721}
4722
4723
Alexander Belopolsky40018472011-02-26 01:02:56 +00004724PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004725_PyUnicode_EncodeUTF7(PyObject *str,
4726 int base64SetO,
4727 int base64WhiteSpace,
4728 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004729{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004730 int kind;
4731 void *data;
4732 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004733 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004735 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004736 unsigned int base64bits = 0;
4737 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004738 char * out;
4739 char * start;
4740
Benjamin Petersonbac79492012-01-14 13:34:47 -05004741 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004742 return NULL;
4743 kind = PyUnicode_KIND(str);
4744 data = PyUnicode_DATA(str);
4745 len = PyUnicode_GET_LENGTH(str);
4746
4747 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004748 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004749
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004750 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004751 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004752 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004753 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004754 if (v == NULL)
4755 return NULL;
4756
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004757 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004758 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004759 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004760
Antoine Pitrou244651a2009-05-04 18:56:13 +00004761 if (inShift) {
4762 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4763 /* shifting out */
4764 if (base64bits) { /* output remaining bits */
4765 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4766 base64buffer = 0;
4767 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768 }
4769 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004770 /* Characters not in the BASE64 set implicitly unshift the sequence
4771 so no '-' is required, except if the character is itself a '-' */
4772 if (IS_BASE64(ch) || ch == '-') {
4773 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004774 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004775 *out++ = (char) ch;
4776 }
4777 else {
4778 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004779 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004780 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004781 else { /* not in a shift sequence */
4782 if (ch == '+') {
4783 *out++ = '+';
4784 *out++ = '-';
4785 }
4786 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4787 *out++ = (char) ch;
4788 }
4789 else {
4790 *out++ = '+';
4791 inShift = 1;
4792 goto encode_char;
4793 }
4794 }
4795 continue;
4796encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004797 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004798 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004799
Antoine Pitrou244651a2009-05-04 18:56:13 +00004800 /* code first surrogate */
4801 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004802 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004803 while (base64bits >= 6) {
4804 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4805 base64bits -= 6;
4806 }
4807 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004808 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004809 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004810 base64bits += 16;
4811 base64buffer = (base64buffer << 16) | ch;
4812 while (base64bits >= 6) {
4813 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4814 base64bits -= 6;
4815 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004816 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004817 if (base64bits)
4818 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4819 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004820 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004821 if (_PyBytes_Resize(&v, out - start) < 0)
4822 return NULL;
4823 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004824}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004825PyObject *
4826PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4827 Py_ssize_t size,
4828 int base64SetO,
4829 int base64WhiteSpace,
4830 const char *errors)
4831{
4832 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004833 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004834 if (tmp == NULL)
4835 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004836 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004837 base64WhiteSpace, errors);
4838 Py_DECREF(tmp);
4839 return result;
4840}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004841
Antoine Pitrou244651a2009-05-04 18:56:13 +00004842#undef IS_BASE64
4843#undef FROM_BASE64
4844#undef TO_BASE64
4845#undef DECODE_DIRECT
4846#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004847
Guido van Rossumd57fd912000-03-10 22:53:23 +00004848/* --- UTF-8 Codec -------------------------------------------------------- */
4849
Alexander Belopolsky40018472011-02-26 01:02:56 +00004850PyObject *
4851PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004852 Py_ssize_t size,
4853 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004854{
Walter Dörwald69652032004-09-07 20:24:22 +00004855 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4856}
4857
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004858#include "stringlib/asciilib.h"
4859#include "stringlib/codecs.h"
4860#include "stringlib/undef.h"
4861
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004862#include "stringlib/ucs1lib.h"
4863#include "stringlib/codecs.h"
4864#include "stringlib/undef.h"
4865
4866#include "stringlib/ucs2lib.h"
4867#include "stringlib/codecs.h"
4868#include "stringlib/undef.h"
4869
4870#include "stringlib/ucs4lib.h"
4871#include "stringlib/codecs.h"
4872#include "stringlib/undef.h"
4873
Antoine Pitrouab868312009-01-10 15:40:25 +00004874/* Mask to quickly check whether a C 'long' contains a
4875 non-ASCII, UTF8-encoded char. */
4876#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004877# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004878#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004879# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004880#else
4881# error C 'long' size should be either 4 or 8!
4882#endif
4883
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004884static Py_ssize_t
4885ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004886{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004887 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004888 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004889
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004890 /*
4891 * Issue #17237: m68k is a bit different from most architectures in
4892 * that objects do not use "natural alignment" - for example, int and
4893 * long are only aligned at 2-byte boundaries. Therefore the assert()
4894 * won't work; also, tests have shown that skipping the "optimised
4895 * version" will even speed up m68k.
4896 */
4897#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004898#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004899 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4900 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004901 /* Fast path, see in STRINGLIB(utf8_decode) for
4902 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004903 /* Help allocation */
4904 const char *_p = p;
4905 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004906 while (_p < aligned_end) {
4907 unsigned long value = *(const unsigned long *) _p;
4908 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004909 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910 *((unsigned long *)q) = value;
4911 _p += SIZEOF_LONG;
4912 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004913 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004914 p = _p;
4915 while (p < end) {
4916 if ((unsigned char)*p & 0x80)
4917 break;
4918 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004919 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004920 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004921 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004922#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004923#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004924 while (p < end) {
4925 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4926 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004927 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004928 /* Help allocation */
4929 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004930 while (_p < aligned_end) {
4931 unsigned long value = *(unsigned long *) _p;
4932 if (value & ASCII_CHAR_MASK)
4933 break;
4934 _p += SIZEOF_LONG;
4935 }
4936 p = _p;
4937 if (_p == end)
4938 break;
4939 }
4940 if ((unsigned char)*p & 0x80)
4941 break;
4942 ++p;
4943 }
4944 memcpy(dest, start, p - start);
4945 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004946}
Antoine Pitrouab868312009-01-10 15:40:25 +00004947
Victor Stinner785938e2011-12-11 20:09:03 +01004948PyObject *
4949PyUnicode_DecodeUTF8Stateful(const char *s,
4950 Py_ssize_t size,
4951 const char *errors,
4952 Py_ssize_t *consumed)
4953{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004954 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004955 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004957
4958 Py_ssize_t startinpos;
4959 Py_ssize_t endinpos;
4960 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004961 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004963 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004964
4965 if (size == 0) {
4966 if (consumed)
4967 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004968 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004969 }
4970
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004971 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4972 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004973 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 *consumed = 1;
4975 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004976 }
4977
Victor Stinner8f674cc2013-04-17 23:02:17 +02004978 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004979 writer.min_length = size;
4980 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004982
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004983 writer.pos = ascii_decode(s, end, writer.data);
4984 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004985 while (s < end) {
4986 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004987 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004988
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004989 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004990 if (PyUnicode_IS_ASCII(writer.buffer))
4991 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004992 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004993 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004994 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004995 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 } else {
4997 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004998 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004999 }
5000
5001 switch (ch) {
5002 case 0:
5003 if (s == end || consumed)
5004 goto End;
5005 errmsg = "unexpected end of data";
5006 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005007 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 break;
5009 case 1:
5010 errmsg = "invalid start byte";
5011 startinpos = s - starts;
5012 endinpos = startinpos + 1;
5013 break;
5014 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005015 case 3:
5016 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005017 errmsg = "invalid continuation byte";
5018 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005019 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005020 break;
5021 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005022 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005023 goto onError;
5024 continue;
5025 }
5026
Victor Stinner1d65d912015-10-05 13:43:50 +02005027 if (error_handler == _Py_ERROR_UNKNOWN)
5028 error_handler = get_error_handler(errors);
5029
5030 switch (error_handler) {
5031 case _Py_ERROR_IGNORE:
5032 s += (endinpos - startinpos);
5033 break;
5034
5035 case _Py_ERROR_REPLACE:
5036 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5037 goto onError;
5038 s += (endinpos - startinpos);
5039 break;
5040
5041 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005042 {
5043 Py_ssize_t i;
5044
Victor Stinner1d65d912015-10-05 13:43:50 +02005045 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5046 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005047 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005048 ch = (Py_UCS4)(unsigned char)(starts[i]);
5049 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5050 ch + 0xdc00);
5051 writer.pos++;
5052 }
5053 s += (endinpos - startinpos);
5054 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005055 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005056
5057 default:
5058 if (unicode_decode_call_errorhandler_writer(
5059 errors, &error_handler_obj,
5060 "utf-8", errmsg,
5061 &starts, &end, &startinpos, &endinpos, &exc, &s,
5062 &writer))
5063 goto onError;
5064 }
Victor Stinner785938e2011-12-11 20:09:03 +01005065 }
5066
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005067End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005068 if (consumed)
5069 *consumed = s - starts;
5070
Victor Stinner1d65d912015-10-05 13:43:50 +02005071 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005072 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005073 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005074
5075onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005076 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005077 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005078 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005079 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005080}
5081
Xavier de Gaye76febd02016-12-15 20:59:58 +01005082#if defined(__APPLE__) || defined(__ANDROID__)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005083
5084/* Simplified UTF-8 decoder using surrogateescape error handler,
Xavier de Gaye76febd02016-12-15 20:59:58 +01005085 used to decode the command line arguments on Mac OS X and Android.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005086
5087 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005088 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005089
5090wchar_t*
5091_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5092{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005093 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005094 wchar_t *unicode;
5095 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005096
5097 /* Note: size will always be longer than the resulting Unicode
5098 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005099 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005100 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005101 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005102 if (!unicode)
5103 return NULL;
5104
5105 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005106 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005107 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005108 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005109 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005110#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005111 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005112#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005113 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005114#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005115 if (ch > 0xFF) {
5116#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005117 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005118#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005119 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005120 /* compute and append the two surrogates: */
5121 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5122 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5123#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005124 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005125 else {
5126 if (!ch && s == e)
5127 break;
5128 /* surrogateescape */
5129 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5130 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005131 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005132 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005133 return unicode;
5134}
5135
Xavier de Gaye76febd02016-12-15 20:59:58 +01005136#endif /* __APPLE__ or __ANDROID__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005138/* Primary internal function which creates utf8 encoded bytes objects.
5139
5140 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005141 and allocate exactly as much space needed at the end. Else allocate the
5142 maximum possible needed (4 result bytes per Unicode character), and return
5143 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005144*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005145PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005146_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005147{
Victor Stinner6099a032011-12-18 14:22:26 +01005148 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005149 void *data;
5150 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005151
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005152 if (!PyUnicode_Check(unicode)) {
5153 PyErr_BadArgument();
5154 return NULL;
5155 }
5156
5157 if (PyUnicode_READY(unicode) == -1)
5158 return NULL;
5159
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005160 if (PyUnicode_UTF8(unicode))
5161 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5162 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005163
5164 kind = PyUnicode_KIND(unicode);
5165 data = PyUnicode_DATA(unicode);
5166 size = PyUnicode_GET_LENGTH(unicode);
5167
Benjamin Petersonead6b532011-12-20 17:23:42 -06005168 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005169 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005170 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005171 case PyUnicode_1BYTE_KIND:
5172 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5173 assert(!PyUnicode_IS_ASCII(unicode));
5174 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5175 case PyUnicode_2BYTE_KIND:
5176 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5177 case PyUnicode_4BYTE_KIND:
5178 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005179 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005180}
5181
Alexander Belopolsky40018472011-02-26 01:02:56 +00005182PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005183PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5184 Py_ssize_t size,
5185 const char *errors)
5186{
5187 PyObject *v, *unicode;
5188
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005189 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005190 if (unicode == NULL)
5191 return NULL;
5192 v = _PyUnicode_AsUTF8String(unicode, errors);
5193 Py_DECREF(unicode);
5194 return v;
5195}
5196
5197PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005198PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005199{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005200 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005201}
5202
Walter Dörwald41980ca2007-08-16 21:55:45 +00005203/* --- UTF-32 Codec ------------------------------------------------------- */
5204
5205PyObject *
5206PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005207 Py_ssize_t size,
5208 const char *errors,
5209 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005210{
5211 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5212}
5213
5214PyObject *
5215PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005216 Py_ssize_t size,
5217 const char *errors,
5218 int *byteorder,
5219 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005220{
5221 const char *starts = s;
5222 Py_ssize_t startinpos;
5223 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005224 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005225 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005226 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005227 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005228 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005229 PyObject *errorHandler = NULL;
5230 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005231
Walter Dörwald41980ca2007-08-16 21:55:45 +00005232 q = (unsigned char *)s;
5233 e = q + size;
5234
5235 if (byteorder)
5236 bo = *byteorder;
5237
5238 /* Check for BOM marks (U+FEFF) in the input and adjust current
5239 byte order setting accordingly. In native mode, the leading BOM
5240 mark is skipped, in all other modes, it is copied to the output
5241 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005242 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005243 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005244 if (bom == 0x0000FEFF) {
5245 bo = -1;
5246 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005247 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005248 else if (bom == 0xFFFE0000) {
5249 bo = 1;
5250 q += 4;
5251 }
5252 if (byteorder)
5253 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005254 }
5255
Victor Stinnere64322e2012-10-30 23:12:47 +01005256 if (q == e) {
5257 if (consumed)
5258 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005259 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005260 }
5261
Victor Stinnere64322e2012-10-30 23:12:47 +01005262#ifdef WORDS_BIGENDIAN
5263 le = bo < 0;
5264#else
5265 le = bo <= 0;
5266#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005267 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005268
Victor Stinner8f674cc2013-04-17 23:02:17 +02005269 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005270 writer.min_length = (e - q + 3) / 4;
5271 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005272 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005273
Victor Stinnere64322e2012-10-30 23:12:47 +01005274 while (1) {
5275 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005276 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005277
Victor Stinnere64322e2012-10-30 23:12:47 +01005278 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005279 enum PyUnicode_Kind kind = writer.kind;
5280 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005281 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005282 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005283 if (le) {
5284 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005285 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005286 if (ch > maxch)
5287 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005288 if (kind != PyUnicode_1BYTE_KIND &&
5289 Py_UNICODE_IS_SURROGATE(ch))
5290 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005291 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005292 q += 4;
5293 } while (q <= last);
5294 }
5295 else {
5296 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005297 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005298 if (ch > maxch)
5299 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005300 if (kind != PyUnicode_1BYTE_KIND &&
5301 Py_UNICODE_IS_SURROGATE(ch))
5302 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005303 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005304 q += 4;
5305 } while (q <= last);
5306 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005307 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005308 }
5309
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005310 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005311 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005312 startinpos = ((const char *)q) - starts;
5313 endinpos = startinpos + 4;
5314 }
5315 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005316 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005318 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005320 startinpos = ((const char *)q) - starts;
5321 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005322 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005323 else {
5324 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005325 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005326 goto onError;
5327 q += 4;
5328 continue;
5329 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005330 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005331 startinpos = ((const char *)q) - starts;
5332 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005334
5335 /* The remaining input chars are ignored if the callback
5336 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005337 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005339 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005341 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005342 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005343 }
5344
Walter Dörwald41980ca2007-08-16 21:55:45 +00005345 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005346 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005347
Walter Dörwald41980ca2007-08-16 21:55:45 +00005348 Py_XDECREF(errorHandler);
5349 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005350 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351
Benjamin Peterson29060642009-01-31 22:14:21 +00005352 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005353 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005354 Py_XDECREF(errorHandler);
5355 Py_XDECREF(exc);
5356 return NULL;
5357}
5358
5359PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005360_PyUnicode_EncodeUTF32(PyObject *str,
5361 const char *errors,
5362 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005363{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005364 enum PyUnicode_Kind kind;
5365 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005366 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005367 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005368 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005369#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005370 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005371#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005372 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005373#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005374 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005375 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005376 PyObject *errorHandler = NULL;
5377 PyObject *exc = NULL;
5378 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005379
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005380 if (!PyUnicode_Check(str)) {
5381 PyErr_BadArgument();
5382 return NULL;
5383 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005384 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005385 return NULL;
5386 kind = PyUnicode_KIND(str);
5387 data = PyUnicode_DATA(str);
5388 len = PyUnicode_GET_LENGTH(str);
5389
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005390 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005391 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005392 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005393 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005394 if (v == NULL)
5395 return NULL;
5396
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005397 /* output buffer is 4-bytes aligned */
5398 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005399 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005400 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005401 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005402 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005403 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005404
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005405 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005406 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005407 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005408 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005409 else
5410 encoding = "utf-32";
5411
5412 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005413 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5414 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005415 }
5416
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005417 pos = 0;
5418 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005419 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005420
5421 if (kind == PyUnicode_2BYTE_KIND) {
5422 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5423 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005424 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005425 else {
5426 assert(kind == PyUnicode_4BYTE_KIND);
5427 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5428 &out, native_ordering);
5429 }
5430 if (pos == len)
5431 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005432
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005433 rep = unicode_encode_call_errorhandler(
5434 errors, &errorHandler,
5435 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005436 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005437 if (!rep)
5438 goto error;
5439
5440 if (PyBytes_Check(rep)) {
5441 repsize = PyBytes_GET_SIZE(rep);
5442 if (repsize & 3) {
5443 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005444 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005445 "surrogates not allowed");
5446 goto error;
5447 }
5448 moreunits = repsize / 4;
5449 }
5450 else {
5451 assert(PyUnicode_Check(rep));
5452 if (PyUnicode_READY(rep) < 0)
5453 goto error;
5454 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5455 if (!PyUnicode_IS_ASCII(rep)) {
5456 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005457 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005458 "surrogates not allowed");
5459 goto error;
5460 }
5461 }
5462
5463 /* four bytes are reserved for each surrogate */
5464 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005465 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005466 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005467 /* integer overflow */
5468 PyErr_NoMemory();
5469 goto error;
5470 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005471 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005472 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005473 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005474 }
5475
5476 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005477 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005478 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005479 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005480 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005481 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5482 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005483 }
5484
5485 Py_CLEAR(rep);
5486 }
5487
5488 /* Cut back to size actually needed. This is necessary for, for example,
5489 encoding of a string containing isolated surrogates and the 'ignore'
5490 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005491 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005492 if (nsize != PyBytes_GET_SIZE(v))
5493 _PyBytes_Resize(&v, nsize);
5494 Py_XDECREF(errorHandler);
5495 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005496 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005497 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005498 error:
5499 Py_XDECREF(rep);
5500 Py_XDECREF(errorHandler);
5501 Py_XDECREF(exc);
5502 Py_XDECREF(v);
5503 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005504}
5505
Alexander Belopolsky40018472011-02-26 01:02:56 +00005506PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005507PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5508 Py_ssize_t size,
5509 const char *errors,
5510 int byteorder)
5511{
5512 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005513 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005514 if (tmp == NULL)
5515 return NULL;
5516 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5517 Py_DECREF(tmp);
5518 return result;
5519}
5520
5521PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005522PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005523{
Victor Stinnerb960b342011-11-20 19:12:52 +01005524 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005525}
5526
Guido van Rossumd57fd912000-03-10 22:53:23 +00005527/* --- UTF-16 Codec ------------------------------------------------------- */
5528
Tim Peters772747b2001-08-09 22:21:55 +00005529PyObject *
5530PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005531 Py_ssize_t size,
5532 const char *errors,
5533 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005534{
Walter Dörwald69652032004-09-07 20:24:22 +00005535 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5536}
5537
5538PyObject *
5539PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005540 Py_ssize_t size,
5541 const char *errors,
5542 int *byteorder,
5543 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005544{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005545 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005546 Py_ssize_t startinpos;
5547 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005548 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005549 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005550 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005551 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005552 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005553 PyObject *errorHandler = NULL;
5554 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005555 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556
Tim Peters772747b2001-08-09 22:21:55 +00005557 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005558 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559
5560 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005561 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005562
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005563 /* Check for BOM marks (U+FEFF) in the input and adjust current
5564 byte order setting accordingly. In native mode, the leading BOM
5565 mark is skipped, in all other modes, it is copied to the output
5566 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005567 if (bo == 0 && size >= 2) {
5568 const Py_UCS4 bom = (q[1] << 8) | q[0];
5569 if (bom == 0xFEFF) {
5570 q += 2;
5571 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005572 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005573 else if (bom == 0xFFFE) {
5574 q += 2;
5575 bo = 1;
5576 }
5577 if (byteorder)
5578 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005579 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005580
Antoine Pitrou63065d72012-05-15 23:48:04 +02005581 if (q == e) {
5582 if (consumed)
5583 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005584 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005585 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005586
Christian Heimes743e0cd2012-10-17 23:52:17 +02005587#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005588 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005589 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005590#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005591 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005592 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005593#endif
Tim Peters772747b2001-08-09 22:21:55 +00005594
Antoine Pitrou63065d72012-05-15 23:48:04 +02005595 /* Note: size will always be longer than the resulting Unicode
5596 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005597 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005598 writer.min_length = (e - q + 1) / 2;
5599 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005600 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005601
Antoine Pitrou63065d72012-05-15 23:48:04 +02005602 while (1) {
5603 Py_UCS4 ch = 0;
5604 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005605 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005606 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005607 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005608 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005609 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005610 native_ordering);
5611 else
5612 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005613 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005614 native_ordering);
5615 } else if (kind == PyUnicode_2BYTE_KIND) {
5616 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005617 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005618 native_ordering);
5619 } else {
5620 assert(kind == PyUnicode_4BYTE_KIND);
5621 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005622 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005623 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005624 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005625 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005626
Antoine Pitrou63065d72012-05-15 23:48:04 +02005627 switch (ch)
5628 {
5629 case 0:
5630 /* remaining byte at the end? (size should be even) */
5631 if (q == e || consumed)
5632 goto End;
5633 errmsg = "truncated data";
5634 startinpos = ((const char *)q) - starts;
5635 endinpos = ((const char *)e) - starts;
5636 break;
5637 /* The remaining input chars are ignored if the callback
5638 chooses to skip the input */
5639 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005640 q -= 2;
5641 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005642 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005643 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005644 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005645 endinpos = ((const char *)e) - starts;
5646 break;
5647 case 2:
5648 errmsg = "illegal encoding";
5649 startinpos = ((const char *)q) - 2 - starts;
5650 endinpos = startinpos + 2;
5651 break;
5652 case 3:
5653 errmsg = "illegal UTF-16 surrogate";
5654 startinpos = ((const char *)q) - 4 - starts;
5655 endinpos = startinpos + 2;
5656 break;
5657 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005658 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005659 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005660 continue;
5661 }
5662
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005663 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005664 errors,
5665 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005666 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005667 &starts,
5668 (const char **)&e,
5669 &startinpos,
5670 &endinpos,
5671 &exc,
5672 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005673 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005674 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675 }
5676
Antoine Pitrou63065d72012-05-15 23:48:04 +02005677End:
Walter Dörwald69652032004-09-07 20:24:22 +00005678 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005679 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005680
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005681 Py_XDECREF(errorHandler);
5682 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005683 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684
Benjamin Peterson29060642009-01-31 22:14:21 +00005685 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005686 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005687 Py_XDECREF(errorHandler);
5688 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005689 return NULL;
5690}
5691
Tim Peters772747b2001-08-09 22:21:55 +00005692PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005693_PyUnicode_EncodeUTF16(PyObject *str,
5694 const char *errors,
5695 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005697 enum PyUnicode_Kind kind;
5698 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005699 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005700 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005701 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005702 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005703#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005704 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005705#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005706 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005707#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005708 const char *encoding;
5709 Py_ssize_t nsize, pos;
5710 PyObject *errorHandler = NULL;
5711 PyObject *exc = NULL;
5712 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005713
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005714 if (!PyUnicode_Check(str)) {
5715 PyErr_BadArgument();
5716 return NULL;
5717 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005718 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005719 return NULL;
5720 kind = PyUnicode_KIND(str);
5721 data = PyUnicode_DATA(str);
5722 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005723
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005724 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005725 if (kind == PyUnicode_4BYTE_KIND) {
5726 const Py_UCS4 *in = (const Py_UCS4 *)data;
5727 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005728 while (in < end) {
5729 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005730 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005731 }
5732 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005733 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005734 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005736 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005737 nsize = len + pairs + (byteorder == 0);
5738 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005739 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005741 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005743 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005744 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005745 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005746 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005747 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005748 }
5749 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005750 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005751 }
Tim Peters772747b2001-08-09 22:21:55 +00005752
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005753 if (kind == PyUnicode_1BYTE_KIND) {
5754 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5755 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005756 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005757
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005758 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005759 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005760 }
5761 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005762 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005763 }
5764 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005765 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005766 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005767
5768 pos = 0;
5769 while (pos < len) {
5770 Py_ssize_t repsize, moreunits;
5771
5772 if (kind == PyUnicode_2BYTE_KIND) {
5773 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5774 &out, native_ordering);
5775 }
5776 else {
5777 assert(kind == PyUnicode_4BYTE_KIND);
5778 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5779 &out, native_ordering);
5780 }
5781 if (pos == len)
5782 break;
5783
5784 rep = unicode_encode_call_errorhandler(
5785 errors, &errorHandler,
5786 encoding, "surrogates not allowed",
5787 str, &exc, pos, pos + 1, &pos);
5788 if (!rep)
5789 goto error;
5790
5791 if (PyBytes_Check(rep)) {
5792 repsize = PyBytes_GET_SIZE(rep);
5793 if (repsize & 1) {
5794 raise_encode_exception(&exc, encoding,
5795 str, pos - 1, pos,
5796 "surrogates not allowed");
5797 goto error;
5798 }
5799 moreunits = repsize / 2;
5800 }
5801 else {
5802 assert(PyUnicode_Check(rep));
5803 if (PyUnicode_READY(rep) < 0)
5804 goto error;
5805 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5806 if (!PyUnicode_IS_ASCII(rep)) {
5807 raise_encode_exception(&exc, encoding,
5808 str, pos - 1, pos,
5809 "surrogates not allowed");
5810 goto error;
5811 }
5812 }
5813
5814 /* two bytes are reserved for each surrogate */
5815 if (moreunits > 1) {
5816 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005817 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005818 /* integer overflow */
5819 PyErr_NoMemory();
5820 goto error;
5821 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005822 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005823 goto error;
5824 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5825 }
5826
5827 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005828 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005829 out += moreunits;
5830 } else /* rep is unicode */ {
5831 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5832 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5833 &out, native_ordering);
5834 }
5835
5836 Py_CLEAR(rep);
5837 }
5838
5839 /* Cut back to size actually needed. This is necessary for, for example,
5840 encoding of a string containing isolated surrogates and the 'ignore' handler
5841 is used. */
5842 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5843 if (nsize != PyBytes_GET_SIZE(v))
5844 _PyBytes_Resize(&v, nsize);
5845 Py_XDECREF(errorHandler);
5846 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005847 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005848 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005849 error:
5850 Py_XDECREF(rep);
5851 Py_XDECREF(errorHandler);
5852 Py_XDECREF(exc);
5853 Py_XDECREF(v);
5854 return NULL;
5855#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856}
5857
Alexander Belopolsky40018472011-02-26 01:02:56 +00005858PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005859PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5860 Py_ssize_t size,
5861 const char *errors,
5862 int byteorder)
5863{
5864 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005865 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005866 if (tmp == NULL)
5867 return NULL;
5868 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5869 Py_DECREF(tmp);
5870 return result;
5871}
5872
5873PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005874PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005876 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877}
5878
5879/* --- Unicode Escape Codec ----------------------------------------------- */
5880
Fredrik Lundh06d12682001-01-24 07:59:11 +00005881static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005882
Alexander Belopolsky40018472011-02-26 01:02:56 +00005883PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005884_PyUnicode_DecodeUnicodeEscape(const char *s,
5885 Py_ssize_t size,
5886 const char *errors,
5887 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005889 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005890 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005892 PyObject *errorHandler = NULL;
5893 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005894
Eric V. Smith42454af2016-10-31 09:22:08 -04005895 // so we can remember if we've seen an invalid escape char or not
5896 *first_invalid_escape = NULL;
5897
Victor Stinner62ec3312016-09-06 17:04:34 -07005898 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005899 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005900 }
5901 /* Escaped strings will always be longer than the resulting
5902 Unicode string, so we start with size here and then reduce the
5903 length after conversion to the true value.
5904 (but if the error callback returns a long replacement string
5905 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005906 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005907 writer.min_length = size;
5908 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5909 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005910 }
5911
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 end = s + size;
5913 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005914 unsigned char c = (unsigned char) *s++;
5915 Py_UCS4 ch;
5916 int count;
5917 Py_ssize_t startinpos;
5918 Py_ssize_t endinpos;
5919 const char *message;
5920
5921#define WRITE_ASCII_CHAR(ch) \
5922 do { \
5923 assert(ch <= 127); \
5924 assert(writer.pos < writer.size); \
5925 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5926 } while(0)
5927
5928#define WRITE_CHAR(ch) \
5929 do { \
5930 if (ch <= writer.maxchar) { \
5931 assert(writer.pos < writer.size); \
5932 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5933 } \
5934 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5935 goto onError; \
5936 } \
5937 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938
5939 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005940 if (c != '\\') {
5941 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942 continue;
5943 }
5944
Victor Stinner62ec3312016-09-06 17:04:34 -07005945 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005946 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005947 if (s >= end) {
5948 message = "\\ at end of string";
5949 goto error;
5950 }
5951 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005952
Victor Stinner62ec3312016-09-06 17:04:34 -07005953 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005954 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005955
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005957 case '\n': continue;
5958 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5959 case '\'': WRITE_ASCII_CHAR('\''); continue;
5960 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5961 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005962 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005963 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5964 case 't': WRITE_ASCII_CHAR('\t'); continue;
5965 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5966 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005967 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005968 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005969 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005970 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971
Benjamin Peterson29060642009-01-31 22:14:21 +00005972 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 case '0': case '1': case '2': case '3':
5974 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005975 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005976 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005977 ch = (ch<<3) + *s++ - '0';
5978 if (s < end && '0' <= *s && *s <= '7') {
5979 ch = (ch<<3) + *s++ - '0';
5980 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005981 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005982 WRITE_CHAR(ch);
5983 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005984
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 /* hex escapes */
5986 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005988 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005989 message = "truncated \\xXX escape";
5990 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991
Benjamin Peterson29060642009-01-31 22:14:21 +00005992 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005994 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005995 message = "truncated \\uXXXX escape";
5996 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005999 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006000 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006001 message = "truncated \\UXXXXXXXX escape";
6002 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006003 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006004 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006005 ch <<= 4;
6006 if (c >= '0' && c <= '9') {
6007 ch += c - '0';
6008 }
6009 else if (c >= 'a' && c <= 'f') {
6010 ch += c - ('a' - 10);
6011 }
6012 else if (c >= 'A' && c <= 'F') {
6013 ch += c - ('A' - 10);
6014 }
6015 else {
6016 break;
6017 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006018 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006019 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006020 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006021 }
6022
6023 /* when we get here, ch is a 32-bit unicode character */
6024 if (ch > MAX_UNICODE) {
6025 message = "illegal Unicode character";
6026 goto error;
6027 }
6028
6029 WRITE_CHAR(ch);
6030 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006031
Benjamin Peterson29060642009-01-31 22:14:21 +00006032 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006033 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006034 if (ucnhash_CAPI == NULL) {
6035 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006036 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6037 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006038 if (ucnhash_CAPI == NULL) {
6039 PyErr_SetString(
6040 PyExc_UnicodeError,
6041 "\\N escapes not supported (can't load unicodedata module)"
6042 );
6043 goto onError;
6044 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006045 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006046
6047 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006048 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006049 const char *start = ++s;
6050 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006051 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006052 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006053 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006054 namelen = s - start;
6055 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006056 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006057 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006058 ch = 0xffffffff; /* in case 'getcode' messes up */
6059 if (namelen <= INT_MAX &&
6060 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6061 &ch, 0)) {
6062 assert(ch <= MAX_UNICODE);
6063 WRITE_CHAR(ch);
6064 continue;
6065 }
6066 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006067 }
6068 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006069 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006070
6071 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006072 if (*first_invalid_escape == NULL) {
6073 *first_invalid_escape = s-1; /* Back up one char, since we've
6074 already incremented s. */
6075 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006076 WRITE_ASCII_CHAR('\\');
6077 WRITE_CHAR(c);
6078 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006080
6081 error:
6082 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006083 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006084 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006085 errors, &errorHandler,
6086 "unicodeescape", message,
6087 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006088 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006089 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006090 }
6091 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6092 goto onError;
6093 }
6094
6095#undef WRITE_ASCII_CHAR
6096#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006098
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006099 Py_XDECREF(errorHandler);
6100 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006101 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006102
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006104 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006105 Py_XDECREF(errorHandler);
6106 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107 return NULL;
6108}
6109
Eric V. Smith42454af2016-10-31 09:22:08 -04006110PyObject *
6111PyUnicode_DecodeUnicodeEscape(const char *s,
6112 Py_ssize_t size,
6113 const char *errors)
6114{
6115 const char *first_invalid_escape;
6116 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6117 &first_invalid_escape);
6118 if (result == NULL)
6119 return NULL;
6120 if (first_invalid_escape != NULL) {
6121 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6122 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006123 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006124 Py_DECREF(result);
6125 return NULL;
6126 }
6127 }
6128 return result;
6129}
6130
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006131/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006132
Alexander Belopolsky40018472011-02-26 01:02:56 +00006133PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006134PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006135{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006136 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006137 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006139 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006140 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006141 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142
Ezio Melottie7f90372012-10-05 03:33:31 +03006143 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006144 escape.
6145
Ezio Melottie7f90372012-10-05 03:33:31 +03006146 For UCS1 strings it's '\xxx', 4 bytes per source character.
6147 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6148 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006149 */
6150
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006151 if (!PyUnicode_Check(unicode)) {
6152 PyErr_BadArgument();
6153 return NULL;
6154 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006155 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006157 }
Victor Stinner358af132015-10-12 22:36:57 +02006158
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006159 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006160 if (len == 0) {
6161 return PyBytes_FromStringAndSize(NULL, 0);
6162 }
6163
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006164 kind = PyUnicode_KIND(unicode);
6165 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006166 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6167 bytes, and 1 byte characters 4. */
6168 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006169 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006170 return PyErr_NoMemory();
6171 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006172 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006173 if (repr == NULL) {
6174 return NULL;
6175 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006176
Victor Stinner62ec3312016-09-06 17:04:34 -07006177 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006178 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006179 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006180
Victor Stinner62ec3312016-09-06 17:04:34 -07006181 /* U+0000-U+00ff range */
6182 if (ch < 0x100) {
6183 if (ch >= ' ' && ch < 127) {
6184 if (ch != '\\') {
6185 /* Copy printable US ASCII as-is */
6186 *p++ = (char) ch;
6187 }
6188 /* Escape backslashes */
6189 else {
6190 *p++ = '\\';
6191 *p++ = '\\';
6192 }
6193 }
Victor Stinner358af132015-10-12 22:36:57 +02006194
Victor Stinner62ec3312016-09-06 17:04:34 -07006195 /* Map special whitespace to '\t', \n', '\r' */
6196 else if (ch == '\t') {
6197 *p++ = '\\';
6198 *p++ = 't';
6199 }
6200 else if (ch == '\n') {
6201 *p++ = '\\';
6202 *p++ = 'n';
6203 }
6204 else if (ch == '\r') {
6205 *p++ = '\\';
6206 *p++ = 'r';
6207 }
6208
6209 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6210 else {
6211 *p++ = '\\';
6212 *p++ = 'x';
6213 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6214 *p++ = Py_hexdigits[ch & 0x000F];
6215 }
Tim Petersced69f82003-09-16 20:30:58 +00006216 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006217 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006218 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219 *p++ = '\\';
6220 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006221 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6222 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6223 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6224 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006226 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6227 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006228
Victor Stinner62ec3312016-09-06 17:04:34 -07006229 /* Make sure that the first two digits are zero */
6230 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006231 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006232 *p++ = 'U';
6233 *p++ = '0';
6234 *p++ = '0';
6235 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6236 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6237 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6238 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6239 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6240 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006241 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006242 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243
Victor Stinner62ec3312016-09-06 17:04:34 -07006244 assert(p - PyBytes_AS_STRING(repr) > 0);
6245 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6246 return NULL;
6247 }
6248 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249}
6250
Alexander Belopolsky40018472011-02-26 01:02:56 +00006251PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006252PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6253 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006255 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006256 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006257 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006258 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006259 }
6260
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006261 result = PyUnicode_AsUnicodeEscapeString(tmp);
6262 Py_DECREF(tmp);
6263 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006264}
6265
6266/* --- Raw Unicode Escape Codec ------------------------------------------- */
6267
Alexander Belopolsky40018472011-02-26 01:02:56 +00006268PyObject *
6269PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006270 Py_ssize_t size,
6271 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006272{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006273 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006274 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006275 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006276 PyObject *errorHandler = NULL;
6277 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006278
Victor Stinner62ec3312016-09-06 17:04:34 -07006279 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006280 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006281 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006282
Guido van Rossumd57fd912000-03-10 22:53:23 +00006283 /* Escaped strings will always be longer than the resulting
6284 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006285 length after conversion to the true value. (But decoding error
6286 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006287 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006288 writer.min_length = size;
6289 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6290 goto onError;
6291 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006292
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293 end = s + size;
6294 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006295 unsigned char c = (unsigned char) *s++;
6296 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006297 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006298 Py_ssize_t startinpos;
6299 Py_ssize_t endinpos;
6300 const char *message;
6301
6302#define WRITE_CHAR(ch) \
6303 do { \
6304 if (ch <= writer.maxchar) { \
6305 assert(writer.pos < writer.size); \
6306 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6307 } \
6308 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6309 goto onError; \
6310 } \
6311 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006312
Benjamin Peterson29060642009-01-31 22:14:21 +00006313 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006314 if (c != '\\' || s >= end) {
6315 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006316 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006317 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006318
Victor Stinner62ec3312016-09-06 17:04:34 -07006319 c = (unsigned char) *s++;
6320 if (c == 'u') {
6321 count = 4;
6322 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006323 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006324 else if (c == 'U') {
6325 count = 8;
6326 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006327 }
6328 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006329 assert(writer.pos < writer.size);
6330 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6331 WRITE_CHAR(c);
6332 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006333 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006334 startinpos = s - starts - 2;
6335
6336 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6337 for (ch = 0; count && s < end; ++s, --count) {
6338 c = (unsigned char)*s;
6339 ch <<= 4;
6340 if (c >= '0' && c <= '9') {
6341 ch += c - '0';
6342 }
6343 else if (c >= 'a' && c <= 'f') {
6344 ch += c - ('a' - 10);
6345 }
6346 else if (c >= 'A' && c <= 'F') {
6347 ch += c - ('A' - 10);
6348 }
6349 else {
6350 break;
6351 }
6352 }
6353 if (!count) {
6354 if (ch <= MAX_UNICODE) {
6355 WRITE_CHAR(ch);
6356 continue;
6357 }
6358 message = "\\Uxxxxxxxx out of range";
6359 }
6360
6361 endinpos = s-starts;
6362 writer.min_length = end - s + writer.pos;
6363 if (unicode_decode_call_errorhandler_writer(
6364 errors, &errorHandler,
6365 "rawunicodeescape", message,
6366 &starts, &end, &startinpos, &endinpos, &exc, &s,
6367 &writer)) {
6368 goto onError;
6369 }
6370 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6371 goto onError;
6372 }
6373
6374#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006375 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006376 Py_XDECREF(errorHandler);
6377 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006378 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006379
Benjamin Peterson29060642009-01-31 22:14:21 +00006380 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006381 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006382 Py_XDECREF(errorHandler);
6383 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006384 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006385
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386}
6387
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006388
Alexander Belopolsky40018472011-02-26 01:02:56 +00006389PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006390PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006391{
Victor Stinner62ec3312016-09-06 17:04:34 -07006392 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006393 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006394 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006395 int kind;
6396 void *data;
6397 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006398
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006399 if (!PyUnicode_Check(unicode)) {
6400 PyErr_BadArgument();
6401 return NULL;
6402 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006403 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006404 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006405 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006406 kind = PyUnicode_KIND(unicode);
6407 data = PyUnicode_DATA(unicode);
6408 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006409 if (kind == PyUnicode_1BYTE_KIND) {
6410 return PyBytes_FromStringAndSize(data, len);
6411 }
Victor Stinner0e368262011-11-10 20:12:49 +01006412
Victor Stinner62ec3312016-09-06 17:04:34 -07006413 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6414 bytes, and 1 byte characters 4. */
6415 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006416
Victor Stinner62ec3312016-09-06 17:04:34 -07006417 if (len > PY_SSIZE_T_MAX / expandsize) {
6418 return PyErr_NoMemory();
6419 }
6420 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6421 if (repr == NULL) {
6422 return NULL;
6423 }
6424 if (len == 0) {
6425 return repr;
6426 }
6427
6428 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006429 for (pos = 0; pos < len; pos++) {
6430 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006431
Victor Stinner62ec3312016-09-06 17:04:34 -07006432 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6433 if (ch < 0x100) {
6434 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006435 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006436 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6437 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006438 *p++ = '\\';
6439 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006440 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6441 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6442 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6443 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006444 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006445 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6446 else {
6447 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6448 *p++ = '\\';
6449 *p++ = 'U';
6450 *p++ = '0';
6451 *p++ = '0';
6452 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6453 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6454 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6455 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6456 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6457 *p++ = Py_hexdigits[ch & 15];
6458 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006459 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006460
Victor Stinner62ec3312016-09-06 17:04:34 -07006461 assert(p > PyBytes_AS_STRING(repr));
6462 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6463 return NULL;
6464 }
6465 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006466}
6467
Alexander Belopolsky40018472011-02-26 01:02:56 +00006468PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006469PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6470 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006471{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006472 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006473 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006474 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006475 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006476 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6477 Py_DECREF(tmp);
6478 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006479}
6480
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006481/* --- Unicode Internal Codec ------------------------------------------- */
6482
Alexander Belopolsky40018472011-02-26 01:02:56 +00006483PyObject *
6484_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006485 Py_ssize_t size,
6486 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006487{
6488 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006489 Py_ssize_t startinpos;
6490 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006491 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006492 const char *end;
6493 const char *reason;
6494 PyObject *errorHandler = NULL;
6495 PyObject *exc = NULL;
6496
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006497 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006498 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006499 1))
6500 return NULL;
6501
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006502 if (size < 0) {
6503 PyErr_BadInternalCall();
6504 return NULL;
6505 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006506 if (size == 0)
6507 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006508
Victor Stinner8f674cc2013-04-17 23:02:17 +02006509 _PyUnicodeWriter_Init(&writer);
6510 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6511 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006513 }
6514 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006515
Victor Stinner8f674cc2013-04-17 23:02:17 +02006516 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006517 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006518 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006519 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006520 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006521 endinpos = end-starts;
6522 reason = "truncated input";
6523 goto error;
6524 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006525 /* We copy the raw representation one byte at a time because the
6526 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006527 ((char *) &uch)[0] = s[0];
6528 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006529#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006530 ((char *) &uch)[2] = s[2];
6531 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006532#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006533 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006534#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006535 /* We have to sanity check the raw data, otherwise doom looms for
6536 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006537 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006538 endinpos = s - starts + Py_UNICODE_SIZE;
6539 reason = "illegal code point (> 0x10FFFF)";
6540 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006541 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006542#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006543 s += Py_UNICODE_SIZE;
6544#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006545 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006546 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006547 Py_UNICODE uch2;
6548 ((char *) &uch2)[0] = s[0];
6549 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006550 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006551 {
Victor Stinner551ac952011-11-29 22:58:13 +01006552 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006553 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006554 }
6555 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006556#endif
6557
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006558 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006559 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006560 continue;
6561
6562 error:
6563 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006564 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006565 errors, &errorHandler,
6566 "unicode_internal", reason,
6567 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006568 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006569 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006570 }
6571
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006572 Py_XDECREF(errorHandler);
6573 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006574 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006575
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006577 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006578 Py_XDECREF(errorHandler);
6579 Py_XDECREF(exc);
6580 return NULL;
6581}
6582
Guido van Rossumd57fd912000-03-10 22:53:23 +00006583/* --- Latin-1 Codec ------------------------------------------------------ */
6584
Alexander Belopolsky40018472011-02-26 01:02:56 +00006585PyObject *
6586PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006587 Py_ssize_t size,
6588 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006589{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006590 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006591 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006592}
6593
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006594/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006595static void
6596make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006597 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006598 PyObject *unicode,
6599 Py_ssize_t startpos, Py_ssize_t endpos,
6600 const char *reason)
6601{
6602 if (*exceptionObject == NULL) {
6603 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006604 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006605 encoding, unicode, startpos, endpos, reason);
6606 }
6607 else {
6608 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6609 goto onError;
6610 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6611 goto onError;
6612 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6613 goto onError;
6614 return;
6615 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006616 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006617 }
6618}
6619
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006620/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006621static void
6622raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006623 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006624 PyObject *unicode,
6625 Py_ssize_t startpos, Py_ssize_t endpos,
6626 const char *reason)
6627{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006628 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006629 encoding, unicode, startpos, endpos, reason);
6630 if (*exceptionObject != NULL)
6631 PyCodec_StrictErrors(*exceptionObject);
6632}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006633
6634/* error handling callback helper:
6635 build arguments, call the callback and check the arguments,
6636 put the result into newpos and return the replacement string, which
6637 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006638static PyObject *
6639unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006640 PyObject **errorHandler,
6641 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006642 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006643 Py_ssize_t startpos, Py_ssize_t endpos,
6644 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006645{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006646 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006648 PyObject *restuple;
6649 PyObject *resunicode;
6650
6651 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006655 }
6656
Benjamin Petersonbac79492012-01-14 13:34:47 -05006657 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006658 return NULL;
6659 len = PyUnicode_GET_LENGTH(unicode);
6660
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006661 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006662 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006664 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006665
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006666 restuple = PyObject_CallFunctionObjArgs(
6667 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006669 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006670 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006671 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006672 Py_DECREF(restuple);
6673 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006674 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006675 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 &resunicode, newpos)) {
6677 Py_DECREF(restuple);
6678 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006679 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006680 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6681 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6682 Py_DECREF(restuple);
6683 return NULL;
6684 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006685 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006686 *newpos = len + *newpos;
6687 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006688 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006689 Py_DECREF(restuple);
6690 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006691 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006692 Py_INCREF(resunicode);
6693 Py_DECREF(restuple);
6694 return resunicode;
6695}
6696
Alexander Belopolsky40018472011-02-26 01:02:56 +00006697static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006698unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006699 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006700 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006701{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006702 /* input state */
6703 Py_ssize_t pos=0, size;
6704 int kind;
6705 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006706 /* pointer into the output */
6707 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006708 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6709 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006710 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006711 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006712 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006713 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006714 /* output object */
6715 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716
Benjamin Petersonbac79492012-01-14 13:34:47 -05006717 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006718 return NULL;
6719 size = PyUnicode_GET_LENGTH(unicode);
6720 kind = PyUnicode_KIND(unicode);
6721 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006722 /* allocate enough for a simple encoding without
6723 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006724 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006725 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006726
6727 _PyBytesWriter_Init(&writer);
6728 str = _PyBytesWriter_Alloc(&writer, size);
6729 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006730 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006731
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006732 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006733 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006734
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006736 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006737 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006738 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006739 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006740 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006742 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006744 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006745 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006747
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006748 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006750
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006751 /* Only overallocate the buffer if it's not the last write */
6752 writer.overallocate = (collend < size);
6753
Benjamin Peterson29060642009-01-31 22:14:21 +00006754 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006755 if (error_handler == _Py_ERROR_UNKNOWN)
6756 error_handler = get_error_handler(errors);
6757
6758 switch (error_handler) {
6759 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006760 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006761 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006762
6763 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006764 memset(str, '?', collend - collstart);
6765 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006766 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006767 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006768 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006769 break;
Victor Stinner50149202015-09-22 00:26:54 +02006770
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006771 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006772 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006773 writer.min_size -= (collend - collstart);
6774 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006775 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006776 if (str == NULL)
6777 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006778 pos = collend;
6779 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006780
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006781 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006782 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006783 writer.min_size -= (collend - collstart);
6784 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006785 unicode, collstart, collend);
6786 if (str == NULL)
6787 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006788 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006789 break;
Victor Stinner50149202015-09-22 00:26:54 +02006790
Victor Stinnerc3713e92015-09-29 12:32:13 +02006791 case _Py_ERROR_SURROGATEESCAPE:
6792 for (i = collstart; i < collend; ++i) {
6793 ch = PyUnicode_READ(kind, data, i);
6794 if (ch < 0xdc80 || 0xdcff < ch) {
6795 /* Not a UTF-8b surrogate */
6796 break;
6797 }
6798 *str++ = (char)(ch - 0xdc00);
6799 ++pos;
6800 }
6801 if (i >= collend)
6802 break;
6803 collstart = pos;
6804 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006805 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006806
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006808 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6809 encoding, reason, unicode, &exc,
6810 collstart, collend, &newpos);
6811 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006812 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006813
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006814 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006815 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006816
Victor Stinner6bd525b2015-10-09 13:10:05 +02006817 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006818 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006819 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006820 PyBytes_AS_STRING(rep),
6821 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006822 if (str == NULL)
6823 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006824 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006825 else {
6826 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006827
Victor Stinner6bd525b2015-10-09 13:10:05 +02006828 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006829 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006830
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006831 if (limit == 256 ?
6832 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6833 !PyUnicode_IS_ASCII(rep))
6834 {
6835 /* Not all characters are smaller than limit */
6836 raise_encode_exception(&exc, encoding, unicode,
6837 collstart, collend, reason);
6838 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006839 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006840 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6841 str = _PyBytesWriter_WriteBytes(&writer, str,
6842 PyUnicode_DATA(rep),
6843 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006844 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006845 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006846 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006847 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006848
6849 /* If overallocation was disabled, ensure that it was the last
6850 write. Otherwise, we missed an optimization */
6851 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006852 }
6853 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006854
Victor Stinner50149202015-09-22 00:26:54 +02006855 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006856 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006857 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006858
6859 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006860 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006861 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006862 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006863 Py_XDECREF(exc);
6864 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006865}
6866
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006867/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006868PyObject *
6869PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006870 Py_ssize_t size,
6871 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006872{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006873 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006874 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006875 if (unicode == NULL)
6876 return NULL;
6877 result = unicode_encode_ucs1(unicode, errors, 256);
6878 Py_DECREF(unicode);
6879 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006880}
6881
Alexander Belopolsky40018472011-02-26 01:02:56 +00006882PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006883_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006884{
6885 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006886 PyErr_BadArgument();
6887 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006888 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006889 if (PyUnicode_READY(unicode) == -1)
6890 return NULL;
6891 /* Fast path: if it is a one-byte string, construct
6892 bytes object directly. */
6893 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6894 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6895 PyUnicode_GET_LENGTH(unicode));
6896 /* Non-Latin-1 characters present. Defer to above function to
6897 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006898 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006899}
6900
6901PyObject*
6902PyUnicode_AsLatin1String(PyObject *unicode)
6903{
6904 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006905}
6906
6907/* --- 7-bit ASCII Codec -------------------------------------------------- */
6908
Alexander Belopolsky40018472011-02-26 01:02:56 +00006909PyObject *
6910PyUnicode_DecodeASCII(const char *s,
6911 Py_ssize_t size,
6912 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006913{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006914 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006915 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006916 int kind;
6917 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006918 Py_ssize_t startinpos;
6919 Py_ssize_t endinpos;
6920 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006921 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006922 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006923 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006924 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006925
Guido van Rossumd57fd912000-03-10 22:53:23 +00006926 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006927 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006928
Guido van Rossumd57fd912000-03-10 22:53:23 +00006929 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006930 if (size == 1 && (unsigned char)s[0] < 128)
6931 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006932
Victor Stinner8f674cc2013-04-17 23:02:17 +02006933 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006934 writer.min_length = size;
6935 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006936 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006937
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006938 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006939 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006940 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006941 writer.pos = outpos;
6942 if (writer.pos == size)
6943 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006944
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006945 s += writer.pos;
6946 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006947 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006948 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006949 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006950 PyUnicode_WRITE(kind, data, writer.pos, c);
6951 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006952 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006953 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006954 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006955
6956 /* byte outsize range 0x00..0x7f: call the error handler */
6957
6958 if (error_handler == _Py_ERROR_UNKNOWN)
6959 error_handler = get_error_handler(errors);
6960
6961 switch (error_handler)
6962 {
6963 case _Py_ERROR_REPLACE:
6964 case _Py_ERROR_SURROGATEESCAPE:
6965 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006966 but we may switch to UCS2 at the first write */
6967 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6968 goto onError;
6969 kind = writer.kind;
6970 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006971
6972 if (error_handler == _Py_ERROR_REPLACE)
6973 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6974 else
6975 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6976 writer.pos++;
6977 ++s;
6978 break;
6979
6980 case _Py_ERROR_IGNORE:
6981 ++s;
6982 break;
6983
6984 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006985 startinpos = s-starts;
6986 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006987 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006988 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006989 "ascii", "ordinal not in range(128)",
6990 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006991 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006992 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006993 kind = writer.kind;
6994 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006995 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006996 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006997 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006998 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006999 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007000
Benjamin Peterson29060642009-01-31 22:14:21 +00007001 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007002 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007003 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007004 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007005 return NULL;
7006}
7007
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007008/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007009PyObject *
7010PyUnicode_EncodeASCII(const Py_UNICODE *p,
7011 Py_ssize_t size,
7012 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007013{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007014 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007015 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007016 if (unicode == NULL)
7017 return NULL;
7018 result = unicode_encode_ucs1(unicode, errors, 128);
7019 Py_DECREF(unicode);
7020 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007021}
7022
Alexander Belopolsky40018472011-02-26 01:02:56 +00007023PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007024_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007025{
7026 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007027 PyErr_BadArgument();
7028 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007029 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007030 if (PyUnicode_READY(unicode) == -1)
7031 return NULL;
7032 /* Fast path: if it is an ASCII-only string, construct bytes object
7033 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007034 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007035 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7036 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007037 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007038}
7039
7040PyObject *
7041PyUnicode_AsASCIIString(PyObject *unicode)
7042{
7043 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007044}
7045
Steve Dowercc16be82016-09-08 10:35:16 -07007046#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007047
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007048/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007049
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007050#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007051#define NEED_RETRY
7052#endif
7053
Victor Stinner3a50e702011-10-18 21:21:00 +02007054#ifndef WC_ERR_INVALID_CHARS
7055# define WC_ERR_INVALID_CHARS 0x0080
7056#endif
7057
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007058static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007059code_page_name(UINT code_page, PyObject **obj)
7060{
7061 *obj = NULL;
7062 if (code_page == CP_ACP)
7063 return "mbcs";
7064 if (code_page == CP_UTF7)
7065 return "CP_UTF7";
7066 if (code_page == CP_UTF8)
7067 return "CP_UTF8";
7068
7069 *obj = PyBytes_FromFormat("cp%u", code_page);
7070 if (*obj == NULL)
7071 return NULL;
7072 return PyBytes_AS_STRING(*obj);
7073}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007074
Victor Stinner3a50e702011-10-18 21:21:00 +02007075static DWORD
7076decode_code_page_flags(UINT code_page)
7077{
7078 if (code_page == CP_UTF7) {
7079 /* The CP_UTF7 decoder only supports flags=0 */
7080 return 0;
7081 }
7082 else
7083 return MB_ERR_INVALID_CHARS;
7084}
7085
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007087 * Decode a byte string from a Windows code page into unicode object in strict
7088 * mode.
7089 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007090 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7091 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007093static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007094decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007095 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007096 const char *in,
7097 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098{
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007100 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007101 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102
7103 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 assert(insize > 0);
7105 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7106 if (outsize <= 0)
7107 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007108
7109 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007110 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007111 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007112 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007113 if (*v == NULL)
7114 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007115 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116 }
7117 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007118 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007119 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007120 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007121 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007122 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007123 }
7124
7125 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007126 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7127 if (outsize <= 0)
7128 goto error;
7129 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007130
Victor Stinner3a50e702011-10-18 21:21:00 +02007131error:
7132 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7133 return -2;
7134 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007135 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007136}
7137
Victor Stinner3a50e702011-10-18 21:21:00 +02007138/*
7139 * Decode a byte string from a code page into unicode object with an error
7140 * handler.
7141 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007142 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007143 * UnicodeDecodeError exception and returns -1 on error.
7144 */
7145static int
7146decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007147 PyObject **v,
7148 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007149 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007150{
7151 const char *startin = in;
7152 const char *endin = in + size;
7153 const DWORD flags = decode_code_page_flags(code_page);
7154 /* Ideally, we should get reason from FormatMessage. This is the Windows
7155 2000 English version of the message. */
7156 const char *reason = "No mapping for the Unicode character exists "
7157 "in the target code page.";
7158 /* each step cannot decode more than 1 character, but a character can be
7159 represented as a surrogate pair */
7160 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007161 int insize;
7162 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 PyObject *errorHandler = NULL;
7164 PyObject *exc = NULL;
7165 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007166 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 DWORD err;
7168 int ret = -1;
7169
7170 assert(size > 0);
7171
7172 encoding = code_page_name(code_page, &encoding_obj);
7173 if (encoding == NULL)
7174 return -1;
7175
Victor Stinner7d00cc12014-03-17 23:08:06 +01007176 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007177 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7178 UnicodeDecodeError. */
7179 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7180 if (exc != NULL) {
7181 PyCodec_StrictErrors(exc);
7182 Py_CLEAR(exc);
7183 }
7184 goto error;
7185 }
7186
7187 if (*v == NULL) {
7188 /* Create unicode object */
7189 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7190 PyErr_NoMemory();
7191 goto error;
7192 }
Victor Stinnerab595942011-12-17 04:59:06 +01007193 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007194 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007195 if (*v == NULL)
7196 goto error;
7197 startout = PyUnicode_AS_UNICODE(*v);
7198 }
7199 else {
7200 /* Extend unicode object */
7201 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7202 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7203 PyErr_NoMemory();
7204 goto error;
7205 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007206 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 goto error;
7208 startout = PyUnicode_AS_UNICODE(*v) + n;
7209 }
7210
7211 /* Decode the byte string character per character */
7212 out = startout;
7213 while (in < endin)
7214 {
7215 /* Decode a character */
7216 insize = 1;
7217 do
7218 {
7219 outsize = MultiByteToWideChar(code_page, flags,
7220 in, insize,
7221 buffer, Py_ARRAY_LENGTH(buffer));
7222 if (outsize > 0)
7223 break;
7224 err = GetLastError();
7225 if (err != ERROR_NO_UNICODE_TRANSLATION
7226 && err != ERROR_INSUFFICIENT_BUFFER)
7227 {
7228 PyErr_SetFromWindowsErr(0);
7229 goto error;
7230 }
7231 insize++;
7232 }
7233 /* 4=maximum length of a UTF-8 sequence */
7234 while (insize <= 4 && (in + insize) <= endin);
7235
7236 if (outsize <= 0) {
7237 Py_ssize_t startinpos, endinpos, outpos;
7238
Victor Stinner7d00cc12014-03-17 23:08:06 +01007239 /* last character in partial decode? */
7240 if (in + insize >= endin && !final)
7241 break;
7242
Victor Stinner3a50e702011-10-18 21:21:00 +02007243 startinpos = in - startin;
7244 endinpos = startinpos + 1;
7245 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007246 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 errors, &errorHandler,
7248 encoding, reason,
7249 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007250 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007251 {
7252 goto error;
7253 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007254 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 }
7256 else {
7257 in += insize;
7258 memcpy(out, buffer, outsize * sizeof(wchar_t));
7259 out += outsize;
7260 }
7261 }
7262
7263 /* write a NUL character at the end */
7264 *out = 0;
7265
7266 /* Extend unicode object */
7267 outsize = out - startout;
7268 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007269 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007270 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007271 /* (in - startin) <= size and size is an int */
7272 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007273
7274error:
7275 Py_XDECREF(encoding_obj);
7276 Py_XDECREF(errorHandler);
7277 Py_XDECREF(exc);
7278 return ret;
7279}
7280
Victor Stinner3a50e702011-10-18 21:21:00 +02007281static PyObject *
7282decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007283 const char *s, Py_ssize_t size,
7284 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007285{
Victor Stinner76a31a62011-11-04 00:05:13 +01007286 PyObject *v = NULL;
7287 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007288
Victor Stinner3a50e702011-10-18 21:21:00 +02007289 if (code_page < 0) {
7290 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7291 return NULL;
7292 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007293 if (size < 0) {
7294 PyErr_BadInternalCall();
7295 return NULL;
7296 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007297
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007298 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007299 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007300
Victor Stinner76a31a62011-11-04 00:05:13 +01007301 do
7302 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007303#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007304 if (size > INT_MAX) {
7305 chunk_size = INT_MAX;
7306 final = 0;
7307 done = 0;
7308 }
7309 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007310#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007311 {
7312 chunk_size = (int)size;
7313 final = (consumed == NULL);
7314 done = 1;
7315 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007316
Victor Stinner76a31a62011-11-04 00:05:13 +01007317 if (chunk_size == 0 && done) {
7318 if (v != NULL)
7319 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007320 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007321 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007322
Victor Stinner76a31a62011-11-04 00:05:13 +01007323 converted = decode_code_page_strict(code_page, &v,
7324 s, chunk_size);
7325 if (converted == -2)
7326 converted = decode_code_page_errors(code_page, &v,
7327 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007328 errors, final);
7329 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007330
7331 if (converted < 0) {
7332 Py_XDECREF(v);
7333 return NULL;
7334 }
7335
7336 if (consumed)
7337 *consumed += converted;
7338
7339 s += converted;
7340 size -= converted;
7341 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007342
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007343 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007344}
7345
Alexander Belopolsky40018472011-02-26 01:02:56 +00007346PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007347PyUnicode_DecodeCodePageStateful(int code_page,
7348 const char *s,
7349 Py_ssize_t size,
7350 const char *errors,
7351 Py_ssize_t *consumed)
7352{
7353 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7354}
7355
7356PyObject *
7357PyUnicode_DecodeMBCSStateful(const char *s,
7358 Py_ssize_t size,
7359 const char *errors,
7360 Py_ssize_t *consumed)
7361{
7362 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7363}
7364
7365PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007366PyUnicode_DecodeMBCS(const char *s,
7367 Py_ssize_t size,
7368 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007369{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007370 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7371}
7372
Victor Stinner3a50e702011-10-18 21:21:00 +02007373static DWORD
7374encode_code_page_flags(UINT code_page, const char *errors)
7375{
7376 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007377 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 }
7379 else if (code_page == CP_UTF7) {
7380 /* CP_UTF7 only supports flags=0 */
7381 return 0;
7382 }
7383 else {
7384 if (errors != NULL && strcmp(errors, "replace") == 0)
7385 return 0;
7386 else
7387 return WC_NO_BEST_FIT_CHARS;
7388 }
7389}
7390
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007391/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 * Encode a Unicode string to a Windows code page into a byte string in strict
7393 * mode.
7394 *
7395 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007396 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007397 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007398static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007399encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007400 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007402{
Victor Stinner554f3f02010-06-16 23:33:54 +00007403 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007404 BOOL *pusedDefaultChar = &usedDefaultChar;
7405 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007406 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007407 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 const DWORD flags = encode_code_page_flags(code_page, NULL);
7409 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007410 /* Create a substring so that we can get the UTF-16 representation
7411 of just the slice under consideration. */
7412 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007413
Martin v. Löwis3d325192011-11-04 18:23:06 +01007414 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007415
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007417 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007419 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007420
Victor Stinner2fc507f2011-11-04 20:06:39 +01007421 substring = PyUnicode_Substring(unicode, offset, offset+len);
7422 if (substring == NULL)
7423 return -1;
7424 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7425 if (p == NULL) {
7426 Py_DECREF(substring);
7427 return -1;
7428 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007429 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007430
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007431 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007433 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 NULL, 0,
7435 NULL, pusedDefaultChar);
7436 if (outsize <= 0)
7437 goto error;
7438 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007439 if (pusedDefaultChar && *pusedDefaultChar) {
7440 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007441 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007442 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007443
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007445 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 if (*outbytes == NULL) {
7448 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007449 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007450 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007452 }
7453 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007454 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 const Py_ssize_t n = PyBytes_Size(*outbytes);
7456 if (outsize > PY_SSIZE_T_MAX - n) {
7457 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007459 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007460 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007461 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7462 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007464 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007465 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007466 }
7467
7468 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007469 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007470 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007471 out, outsize,
7472 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007473 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007474 if (outsize <= 0)
7475 goto error;
7476 if (pusedDefaultChar && *pusedDefaultChar)
7477 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007478 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007479
Victor Stinner3a50e702011-10-18 21:21:00 +02007480error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007481 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7483 return -2;
7484 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007485 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007486}
7487
Victor Stinner3a50e702011-10-18 21:21:00 +02007488/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007489 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 * error handler.
7491 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007492 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007493 * -1 on other error.
7494 */
7495static int
7496encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007497 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007498 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007499{
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007501 Py_ssize_t pos = unicode_offset;
7502 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007503 /* Ideally, we should get reason from FormatMessage. This is the Windows
7504 2000 English version of the message. */
7505 const char *reason = "invalid character";
7506 /* 4=maximum length of a UTF-8 sequence */
7507 char buffer[4];
7508 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7509 Py_ssize_t outsize;
7510 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007511 PyObject *errorHandler = NULL;
7512 PyObject *exc = NULL;
7513 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007514 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007515 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007516 PyObject *rep;
7517 int ret = -1;
7518
7519 assert(insize > 0);
7520
7521 encoding = code_page_name(code_page, &encoding_obj);
7522 if (encoding == NULL)
7523 return -1;
7524
7525 if (errors == NULL || strcmp(errors, "strict") == 0) {
7526 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7527 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007528 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007529 if (exc != NULL) {
7530 PyCodec_StrictErrors(exc);
7531 Py_DECREF(exc);
7532 }
7533 Py_XDECREF(encoding_obj);
7534 return -1;
7535 }
7536
7537 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7538 pusedDefaultChar = &usedDefaultChar;
7539 else
7540 pusedDefaultChar = NULL;
7541
7542 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7543 PyErr_NoMemory();
7544 goto error;
7545 }
7546 outsize = insize * Py_ARRAY_LENGTH(buffer);
7547
7548 if (*outbytes == NULL) {
7549 /* Create string object */
7550 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7551 if (*outbytes == NULL)
7552 goto error;
7553 out = PyBytes_AS_STRING(*outbytes);
7554 }
7555 else {
7556 /* Extend string object */
7557 Py_ssize_t n = PyBytes_Size(*outbytes);
7558 if (n > PY_SSIZE_T_MAX - outsize) {
7559 PyErr_NoMemory();
7560 goto error;
7561 }
7562 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7563 goto error;
7564 out = PyBytes_AS_STRING(*outbytes) + n;
7565 }
7566
7567 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007568 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007569 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007570 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7571 wchar_t chars[2];
7572 int charsize;
7573 if (ch < 0x10000) {
7574 chars[0] = (wchar_t)ch;
7575 charsize = 1;
7576 }
7577 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007578 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7579 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007580 charsize = 2;
7581 }
7582
Victor Stinner3a50e702011-10-18 21:21:00 +02007583 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007584 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007585 buffer, Py_ARRAY_LENGTH(buffer),
7586 NULL, pusedDefaultChar);
7587 if (outsize > 0) {
7588 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7589 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007590 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007591 memcpy(out, buffer, outsize);
7592 out += outsize;
7593 continue;
7594 }
7595 }
7596 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7597 PyErr_SetFromWindowsErr(0);
7598 goto error;
7599 }
7600
Victor Stinner3a50e702011-10-18 21:21:00 +02007601 rep = unicode_encode_call_errorhandler(
7602 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007603 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007604 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007605 if (rep == NULL)
7606 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007607 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007608
7609 if (PyBytes_Check(rep)) {
7610 outsize = PyBytes_GET_SIZE(rep);
7611 if (outsize != 1) {
7612 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7613 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7614 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7615 Py_DECREF(rep);
7616 goto error;
7617 }
7618 out = PyBytes_AS_STRING(*outbytes) + offset;
7619 }
7620 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7621 out += outsize;
7622 }
7623 else {
7624 Py_ssize_t i;
7625 enum PyUnicode_Kind kind;
7626 void *data;
7627
Benjamin Petersonbac79492012-01-14 13:34:47 -05007628 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007629 Py_DECREF(rep);
7630 goto error;
7631 }
7632
7633 outsize = PyUnicode_GET_LENGTH(rep);
7634 if (outsize != 1) {
7635 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7636 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7637 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7638 Py_DECREF(rep);
7639 goto error;
7640 }
7641 out = PyBytes_AS_STRING(*outbytes) + offset;
7642 }
7643 kind = PyUnicode_KIND(rep);
7644 data = PyUnicode_DATA(rep);
7645 for (i=0; i < outsize; i++) {
7646 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7647 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007648 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007649 encoding, unicode,
7650 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007651 "unable to encode error handler result to ASCII");
7652 Py_DECREF(rep);
7653 goto error;
7654 }
7655 *out = (unsigned char)ch;
7656 out++;
7657 }
7658 }
7659 Py_DECREF(rep);
7660 }
7661 /* write a NUL byte */
7662 *out = 0;
7663 outsize = out - PyBytes_AS_STRING(*outbytes);
7664 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7665 if (_PyBytes_Resize(outbytes, outsize) < 0)
7666 goto error;
7667 ret = 0;
7668
7669error:
7670 Py_XDECREF(encoding_obj);
7671 Py_XDECREF(errorHandler);
7672 Py_XDECREF(exc);
7673 return ret;
7674}
7675
Victor Stinner3a50e702011-10-18 21:21:00 +02007676static PyObject *
7677encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007678 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007679 const char *errors)
7680{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007681 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007682 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007683 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007684 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007685
Victor Stinner29dacf22015-01-26 16:41:32 +01007686 if (!PyUnicode_Check(unicode)) {
7687 PyErr_BadArgument();
7688 return NULL;
7689 }
7690
Benjamin Petersonbac79492012-01-14 13:34:47 -05007691 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007692 return NULL;
7693 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007694
Victor Stinner3a50e702011-10-18 21:21:00 +02007695 if (code_page < 0) {
7696 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7697 return NULL;
7698 }
7699
Martin v. Löwis3d325192011-11-04 18:23:06 +01007700 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007701 return PyBytes_FromStringAndSize(NULL, 0);
7702
Victor Stinner7581cef2011-11-03 22:32:33 +01007703 offset = 0;
7704 do
7705 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007706#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007707 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007708 chunks. */
7709 if (len > INT_MAX/2) {
7710 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007711 done = 0;
7712 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007713 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007714#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007715 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007716 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007717 done = 1;
7718 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007719
Victor Stinner76a31a62011-11-04 00:05:13 +01007720 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007721 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007722 errors);
7723 if (ret == -2)
7724 ret = encode_code_page_errors(code_page, &outbytes,
7725 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007726 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007727 if (ret < 0) {
7728 Py_XDECREF(outbytes);
7729 return NULL;
7730 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007731
Victor Stinner7581cef2011-11-03 22:32:33 +01007732 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007733 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007734 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007735
Victor Stinner3a50e702011-10-18 21:21:00 +02007736 return outbytes;
7737}
7738
7739PyObject *
7740PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7741 Py_ssize_t size,
7742 const char *errors)
7743{
Victor Stinner7581cef2011-11-03 22:32:33 +01007744 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007745 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007746 if (unicode == NULL)
7747 return NULL;
7748 res = encode_code_page(CP_ACP, unicode, errors);
7749 Py_DECREF(unicode);
7750 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007751}
7752
7753PyObject *
7754PyUnicode_EncodeCodePage(int code_page,
7755 PyObject *unicode,
7756 const char *errors)
7757{
Victor Stinner7581cef2011-11-03 22:32:33 +01007758 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007759}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007760
Alexander Belopolsky40018472011-02-26 01:02:56 +00007761PyObject *
7762PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007763{
Victor Stinner7581cef2011-11-03 22:32:33 +01007764 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007765}
7766
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007767#undef NEED_RETRY
7768
Steve Dowercc16be82016-09-08 10:35:16 -07007769#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007770
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771/* --- Character Mapping Codec -------------------------------------------- */
7772
Victor Stinnerfb161b12013-04-18 01:44:27 +02007773static int
7774charmap_decode_string(const char *s,
7775 Py_ssize_t size,
7776 PyObject *mapping,
7777 const char *errors,
7778 _PyUnicodeWriter *writer)
7779{
7780 const char *starts = s;
7781 const char *e;
7782 Py_ssize_t startinpos, endinpos;
7783 PyObject *errorHandler = NULL, *exc = NULL;
7784 Py_ssize_t maplen;
7785 enum PyUnicode_Kind mapkind;
7786 void *mapdata;
7787 Py_UCS4 x;
7788 unsigned char ch;
7789
7790 if (PyUnicode_READY(mapping) == -1)
7791 return -1;
7792
7793 maplen = PyUnicode_GET_LENGTH(mapping);
7794 mapdata = PyUnicode_DATA(mapping);
7795 mapkind = PyUnicode_KIND(mapping);
7796
7797 e = s + size;
7798
7799 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7800 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7801 * is disabled in encoding aliases, latin1 is preferred because
7802 * its implementation is faster. */
7803 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7804 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7805 Py_UCS4 maxchar = writer->maxchar;
7806
7807 assert (writer->kind == PyUnicode_1BYTE_KIND);
7808 while (s < e) {
7809 ch = *s;
7810 x = mapdata_ucs1[ch];
7811 if (x > maxchar) {
7812 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7813 goto onError;
7814 maxchar = writer->maxchar;
7815 outdata = (Py_UCS1 *)writer->data;
7816 }
7817 outdata[writer->pos] = x;
7818 writer->pos++;
7819 ++s;
7820 }
7821 return 0;
7822 }
7823
7824 while (s < e) {
7825 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7826 enum PyUnicode_Kind outkind = writer->kind;
7827 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7828 if (outkind == PyUnicode_1BYTE_KIND) {
7829 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7830 Py_UCS4 maxchar = writer->maxchar;
7831 while (s < e) {
7832 ch = *s;
7833 x = mapdata_ucs2[ch];
7834 if (x > maxchar)
7835 goto Error;
7836 outdata[writer->pos] = x;
7837 writer->pos++;
7838 ++s;
7839 }
7840 break;
7841 }
7842 else if (outkind == PyUnicode_2BYTE_KIND) {
7843 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7844 while (s < e) {
7845 ch = *s;
7846 x = mapdata_ucs2[ch];
7847 if (x == 0xFFFE)
7848 goto Error;
7849 outdata[writer->pos] = x;
7850 writer->pos++;
7851 ++s;
7852 }
7853 break;
7854 }
7855 }
7856 ch = *s;
7857
7858 if (ch < maplen)
7859 x = PyUnicode_READ(mapkind, mapdata, ch);
7860 else
7861 x = 0xfffe; /* invalid value */
7862Error:
7863 if (x == 0xfffe)
7864 {
7865 /* undefined mapping */
7866 startinpos = s-starts;
7867 endinpos = startinpos+1;
7868 if (unicode_decode_call_errorhandler_writer(
7869 errors, &errorHandler,
7870 "charmap", "character maps to <undefined>",
7871 &starts, &e, &startinpos, &endinpos, &exc, &s,
7872 writer)) {
7873 goto onError;
7874 }
7875 continue;
7876 }
7877
7878 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7879 goto onError;
7880 ++s;
7881 }
7882 Py_XDECREF(errorHandler);
7883 Py_XDECREF(exc);
7884 return 0;
7885
7886onError:
7887 Py_XDECREF(errorHandler);
7888 Py_XDECREF(exc);
7889 return -1;
7890}
7891
7892static int
7893charmap_decode_mapping(const char *s,
7894 Py_ssize_t size,
7895 PyObject *mapping,
7896 const char *errors,
7897 _PyUnicodeWriter *writer)
7898{
7899 const char *starts = s;
7900 const char *e;
7901 Py_ssize_t startinpos, endinpos;
7902 PyObject *errorHandler = NULL, *exc = NULL;
7903 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007904 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007905
7906 e = s + size;
7907
7908 while (s < e) {
7909 ch = *s;
7910
7911 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7912 key = PyLong_FromLong((long)ch);
7913 if (key == NULL)
7914 goto onError;
7915
7916 item = PyObject_GetItem(mapping, key);
7917 Py_DECREF(key);
7918 if (item == NULL) {
7919 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7920 /* No mapping found means: mapping is undefined. */
7921 PyErr_Clear();
7922 goto Undefined;
7923 } else
7924 goto onError;
7925 }
7926
7927 /* Apply mapping */
7928 if (item == Py_None)
7929 goto Undefined;
7930 if (PyLong_Check(item)) {
7931 long value = PyLong_AS_LONG(item);
7932 if (value == 0xFFFE)
7933 goto Undefined;
7934 if (value < 0 || value > MAX_UNICODE) {
7935 PyErr_Format(PyExc_TypeError,
7936 "character mapping must be in range(0x%lx)",
7937 (unsigned long)MAX_UNICODE + 1);
7938 goto onError;
7939 }
7940
7941 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7942 goto onError;
7943 }
7944 else if (PyUnicode_Check(item)) {
7945 if (PyUnicode_READY(item) == -1)
7946 goto onError;
7947 if (PyUnicode_GET_LENGTH(item) == 1) {
7948 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7949 if (value == 0xFFFE)
7950 goto Undefined;
7951 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7952 goto onError;
7953 }
7954 else {
7955 writer->overallocate = 1;
7956 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7957 goto onError;
7958 }
7959 }
7960 else {
7961 /* wrong return value */
7962 PyErr_SetString(PyExc_TypeError,
7963 "character mapping must return integer, None or str");
7964 goto onError;
7965 }
7966 Py_CLEAR(item);
7967 ++s;
7968 continue;
7969
7970Undefined:
7971 /* undefined mapping */
7972 Py_CLEAR(item);
7973 startinpos = s-starts;
7974 endinpos = startinpos+1;
7975 if (unicode_decode_call_errorhandler_writer(
7976 errors, &errorHandler,
7977 "charmap", "character maps to <undefined>",
7978 &starts, &e, &startinpos, &endinpos, &exc, &s,
7979 writer)) {
7980 goto onError;
7981 }
7982 }
7983 Py_XDECREF(errorHandler);
7984 Py_XDECREF(exc);
7985 return 0;
7986
7987onError:
7988 Py_XDECREF(item);
7989 Py_XDECREF(errorHandler);
7990 Py_XDECREF(exc);
7991 return -1;
7992}
7993
Alexander Belopolsky40018472011-02-26 01:02:56 +00007994PyObject *
7995PyUnicode_DecodeCharmap(const char *s,
7996 Py_ssize_t size,
7997 PyObject *mapping,
7998 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008000 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008001
Guido van Rossumd57fd912000-03-10 22:53:23 +00008002 /* Default to Latin-1 */
8003 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008004 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008005
Guido van Rossumd57fd912000-03-10 22:53:23 +00008006 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008007 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008008 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008009 writer.min_length = size;
8010 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008011 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008012
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008013 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008014 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8015 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008016 }
8017 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008018 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8019 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008020 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008021 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008022
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008024 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008025 return NULL;
8026}
8027
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028/* Charmap encoding: the lookup table */
8029
Alexander Belopolsky40018472011-02-26 01:02:56 +00008030struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008031 PyObject_HEAD
8032 unsigned char level1[32];
8033 int count2, count3;
8034 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008035};
8036
8037static PyObject*
8038encoding_map_size(PyObject *obj, PyObject* args)
8039{
8040 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008041 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008042 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008043}
8044
8045static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008046 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008047 PyDoc_STR("Return the size (in bytes) of this object") },
8048 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008049};
8050
8051static void
8052encoding_map_dealloc(PyObject* o)
8053{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008054 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055}
8056
8057static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008058 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 "EncodingMap", /*tp_name*/
8060 sizeof(struct encoding_map), /*tp_basicsize*/
8061 0, /*tp_itemsize*/
8062 /* methods */
8063 encoding_map_dealloc, /*tp_dealloc*/
8064 0, /*tp_print*/
8065 0, /*tp_getattr*/
8066 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008067 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008068 0, /*tp_repr*/
8069 0, /*tp_as_number*/
8070 0, /*tp_as_sequence*/
8071 0, /*tp_as_mapping*/
8072 0, /*tp_hash*/
8073 0, /*tp_call*/
8074 0, /*tp_str*/
8075 0, /*tp_getattro*/
8076 0, /*tp_setattro*/
8077 0, /*tp_as_buffer*/
8078 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8079 0, /*tp_doc*/
8080 0, /*tp_traverse*/
8081 0, /*tp_clear*/
8082 0, /*tp_richcompare*/
8083 0, /*tp_weaklistoffset*/
8084 0, /*tp_iter*/
8085 0, /*tp_iternext*/
8086 encoding_map_methods, /*tp_methods*/
8087 0, /*tp_members*/
8088 0, /*tp_getset*/
8089 0, /*tp_base*/
8090 0, /*tp_dict*/
8091 0, /*tp_descr_get*/
8092 0, /*tp_descr_set*/
8093 0, /*tp_dictoffset*/
8094 0, /*tp_init*/
8095 0, /*tp_alloc*/
8096 0, /*tp_new*/
8097 0, /*tp_free*/
8098 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008099};
8100
8101PyObject*
8102PyUnicode_BuildEncodingMap(PyObject* string)
8103{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104 PyObject *result;
8105 struct encoding_map *mresult;
8106 int i;
8107 int need_dict = 0;
8108 unsigned char level1[32];
8109 unsigned char level2[512];
8110 unsigned char *mlevel1, *mlevel2, *mlevel3;
8111 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008112 int kind;
8113 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008114 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008115 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008116
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008117 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008118 PyErr_BadArgument();
8119 return NULL;
8120 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008121 kind = PyUnicode_KIND(string);
8122 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008123 length = PyUnicode_GET_LENGTH(string);
8124 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008125 memset(level1, 0xFF, sizeof level1);
8126 memset(level2, 0xFF, sizeof level2);
8127
8128 /* If there isn't a one-to-one mapping of NULL to \0,
8129 or if there are non-BMP characters, we need to use
8130 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008131 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008132 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008133 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008135 ch = PyUnicode_READ(kind, data, i);
8136 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008137 need_dict = 1;
8138 break;
8139 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008140 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008141 /* unmapped character */
8142 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008143 l1 = ch >> 11;
8144 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008145 if (level1[l1] == 0xFF)
8146 level1[l1] = count2++;
8147 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008148 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008149 }
8150
8151 if (count2 >= 0xFF || count3 >= 0xFF)
8152 need_dict = 1;
8153
8154 if (need_dict) {
8155 PyObject *result = PyDict_New();
8156 PyObject *key, *value;
8157 if (!result)
8158 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008159 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008160 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008161 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008162 if (!key || !value)
8163 goto failed1;
8164 if (PyDict_SetItem(result, key, value) == -1)
8165 goto failed1;
8166 Py_DECREF(key);
8167 Py_DECREF(value);
8168 }
8169 return result;
8170 failed1:
8171 Py_XDECREF(key);
8172 Py_XDECREF(value);
8173 Py_DECREF(result);
8174 return NULL;
8175 }
8176
8177 /* Create a three-level trie */
8178 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8179 16*count2 + 128*count3 - 1);
8180 if (!result)
8181 return PyErr_NoMemory();
8182 PyObject_Init(result, &EncodingMapType);
8183 mresult = (struct encoding_map*)result;
8184 mresult->count2 = count2;
8185 mresult->count3 = count3;
8186 mlevel1 = mresult->level1;
8187 mlevel2 = mresult->level23;
8188 mlevel3 = mresult->level23 + 16*count2;
8189 memcpy(mlevel1, level1, 32);
8190 memset(mlevel2, 0xFF, 16*count2);
8191 memset(mlevel3, 0, 128*count3);
8192 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008193 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008194 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008195 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8196 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008197 /* unmapped character */
8198 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008199 o1 = ch>>11;
8200 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008201 i2 = 16*mlevel1[o1] + o2;
8202 if (mlevel2[i2] == 0xFF)
8203 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008204 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008205 i3 = 128*mlevel2[i2] + o3;
8206 mlevel3[i3] = i;
8207 }
8208 return result;
8209}
8210
8211static int
Victor Stinner22168992011-11-20 17:09:18 +01008212encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008213{
8214 struct encoding_map *map = (struct encoding_map*)mapping;
8215 int l1 = c>>11;
8216 int l2 = (c>>7) & 0xF;
8217 int l3 = c & 0x7F;
8218 int i;
8219
Victor Stinner22168992011-11-20 17:09:18 +01008220 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008221 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008222 if (c == 0)
8223 return 0;
8224 /* level 1*/
8225 i = map->level1[l1];
8226 if (i == 0xFF) {
8227 return -1;
8228 }
8229 /* level 2*/
8230 i = map->level23[16*i+l2];
8231 if (i == 0xFF) {
8232 return -1;
8233 }
8234 /* level 3 */
8235 i = map->level23[16*map->count2 + 128*i + l3];
8236 if (i == 0) {
8237 return -1;
8238 }
8239 return i;
8240}
8241
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242/* Lookup the character ch in the mapping. If the character
8243 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008244 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008245static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008246charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008247{
Christian Heimes217cfd12007-12-02 14:31:20 +00008248 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008249 PyObject *x;
8250
8251 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008253 x = PyObject_GetItem(mapping, w);
8254 Py_DECREF(w);
8255 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8257 /* No mapping found means: mapping is undefined. */
8258 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008259 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 } else
8261 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008262 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008263 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008265 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 long value = PyLong_AS_LONG(x);
8267 if (value < 0 || value > 255) {
8268 PyErr_SetString(PyExc_TypeError,
8269 "character mapping must be in range(256)");
8270 Py_DECREF(x);
8271 return NULL;
8272 }
8273 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008274 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008275 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008277 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 /* wrong return value */
8279 PyErr_Format(PyExc_TypeError,
8280 "character mapping must return integer, bytes or None, not %.400s",
8281 x->ob_type->tp_name);
8282 Py_DECREF(x);
8283 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008284 }
8285}
8286
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008287static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008288charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008289{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008290 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8291 /* exponentially overallocate to minimize reallocations */
8292 if (requiredsize < 2*outsize)
8293 requiredsize = 2*outsize;
8294 if (_PyBytes_Resize(outobj, requiredsize))
8295 return -1;
8296 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008297}
8298
Benjamin Peterson14339b62009-01-31 16:36:08 +00008299typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008301} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008303 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304 space is available. Return a new reference to the object that
8305 was put in the output buffer, or Py_None, if the mapping was undefined
8306 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008307 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008308static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008309charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008310 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008311{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008312 PyObject *rep;
8313 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008314 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008315
Christian Heimes90aa7642007-12-19 02:45:37 +00008316 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008317 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008319 if (res == -1)
8320 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 if (outsize<requiredsize)
8322 if (charmapencode_resize(outobj, outpos, requiredsize))
8323 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008324 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 outstart[(*outpos)++] = (char)res;
8326 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008327 }
8328
8329 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008332 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 Py_DECREF(rep);
8334 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008335 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008336 if (PyLong_Check(rep)) {
8337 Py_ssize_t requiredsize = *outpos+1;
8338 if (outsize<requiredsize)
8339 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8340 Py_DECREF(rep);
8341 return enc_EXCEPTION;
8342 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008343 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008345 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008346 else {
8347 const char *repchars = PyBytes_AS_STRING(rep);
8348 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8349 Py_ssize_t requiredsize = *outpos+repsize;
8350 if (outsize<requiredsize)
8351 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8352 Py_DECREF(rep);
8353 return enc_EXCEPTION;
8354 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008355 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 memcpy(outstart + *outpos, repchars, repsize);
8357 *outpos += repsize;
8358 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008360 Py_DECREF(rep);
8361 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362}
8363
8364/* handle an error in PyUnicode_EncodeCharmap
8365 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008366static int
8367charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008368 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008370 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008371 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008372{
8373 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008374 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008375 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008376 enum PyUnicode_Kind kind;
8377 void *data;
8378 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008380 Py_ssize_t collstartpos = *inpos;
8381 Py_ssize_t collendpos = *inpos+1;
8382 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008383 const char *encoding = "charmap";
8384 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008385 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008386 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008387 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388
Benjamin Petersonbac79492012-01-14 13:34:47 -05008389 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008390 return -1;
8391 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 /* find all unencodable characters */
8393 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008394 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008395 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008396 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008397 val = encoding_map_lookup(ch, mapping);
8398 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008399 break;
8400 ++collendpos;
8401 continue;
8402 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008403
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008404 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8405 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 if (rep==NULL)
8407 return -1;
8408 else if (rep!=Py_None) {
8409 Py_DECREF(rep);
8410 break;
8411 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008412 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 }
8415 /* cache callback name lookup
8416 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008417 if (*error_handler == _Py_ERROR_UNKNOWN)
8418 *error_handler = get_error_handler(errors);
8419
8420 switch (*error_handler) {
8421 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008422 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008423 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008424
8425 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008426 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 x = charmapencode_output('?', mapping, res, respos);
8428 if (x==enc_EXCEPTION) {
8429 return -1;
8430 }
8431 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008432 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 return -1;
8434 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008435 }
8436 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008437 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008438 *inpos = collendpos;
8439 break;
Victor Stinner50149202015-09-22 00:26:54 +02008440
8441 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008442 /* generate replacement (temporarily (mis)uses p) */
8443 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 char buffer[2+29+1+1];
8445 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008446 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 for (cp = buffer; *cp; ++cp) {
8448 x = charmapencode_output(*cp, mapping, res, respos);
8449 if (x==enc_EXCEPTION)
8450 return -1;
8451 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008452 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 return -1;
8454 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008455 }
8456 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008457 *inpos = collendpos;
8458 break;
Victor Stinner50149202015-09-22 00:26:54 +02008459
Benjamin Peterson14339b62009-01-31 16:36:08 +00008460 default:
Victor Stinner50149202015-09-22 00:26:54 +02008461 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008462 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008464 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008466 if (PyBytes_Check(repunicode)) {
8467 /* Directly copy bytes result to output. */
8468 Py_ssize_t outsize = PyBytes_Size(*res);
8469 Py_ssize_t requiredsize;
8470 repsize = PyBytes_Size(repunicode);
8471 requiredsize = *respos + repsize;
8472 if (requiredsize > outsize)
8473 /* Make room for all additional bytes. */
8474 if (charmapencode_resize(res, respos, requiredsize)) {
8475 Py_DECREF(repunicode);
8476 return -1;
8477 }
8478 memcpy(PyBytes_AsString(*res) + *respos,
8479 PyBytes_AsString(repunicode), repsize);
8480 *respos += repsize;
8481 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008482 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008483 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008484 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008485 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008486 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008487 Py_DECREF(repunicode);
8488 return -1;
8489 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008490 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008491 data = PyUnicode_DATA(repunicode);
8492 kind = PyUnicode_KIND(repunicode);
8493 for (index = 0; index < repsize; index++) {
8494 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8495 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008497 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 return -1;
8499 }
8500 else if (x==enc_FAILED) {
8501 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008502 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 return -1;
8504 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008505 }
8506 *inpos = newpos;
8507 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508 }
8509 return 0;
8510}
8511
Alexander Belopolsky40018472011-02-26 01:02:56 +00008512PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008513_PyUnicode_EncodeCharmap(PyObject *unicode,
8514 PyObject *mapping,
8515 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008516{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008517 /* output object */
8518 PyObject *res = NULL;
8519 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008520 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008521 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008523 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008524 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008526 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008527 void *data;
8528 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008529
Benjamin Petersonbac79492012-01-14 13:34:47 -05008530 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008531 return NULL;
8532 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008533 data = PyUnicode_DATA(unicode);
8534 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008535
Guido van Rossumd57fd912000-03-10 22:53:23 +00008536 /* Default to Latin-1 */
8537 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008538 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008540 /* allocate enough for a simple encoding without
8541 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008542 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008543 if (res == NULL)
8544 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008545 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008547
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008549 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008551 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 if (x==enc_EXCEPTION) /* error */
8553 goto onError;
8554 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008555 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008557 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 &res, &respos)) {
8559 goto onError;
8560 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008561 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 else
8563 /* done with this character => adjust input position */
8564 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008565 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008567 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008568 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008569 if (_PyBytes_Resize(&res, respos) < 0)
8570 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008571
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008572 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008573 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574 return res;
8575
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 Py_XDECREF(res);
8578 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008579 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008580 return NULL;
8581}
8582
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008583/* Deprecated */
8584PyObject *
8585PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8586 Py_ssize_t size,
8587 PyObject *mapping,
8588 const char *errors)
8589{
8590 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008591 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008592 if (unicode == NULL)
8593 return NULL;
8594 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8595 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008596 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008597}
8598
Alexander Belopolsky40018472011-02-26 01:02:56 +00008599PyObject *
8600PyUnicode_AsCharmapString(PyObject *unicode,
8601 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008602{
8603 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 PyErr_BadArgument();
8605 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008606 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008607 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608}
8609
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008611static void
8612make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008614 Py_ssize_t startpos, Py_ssize_t endpos,
8615 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008616{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 *exceptionObject = _PyUnicodeTranslateError_Create(
8619 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008620 }
8621 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8623 goto onError;
8624 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8625 goto onError;
8626 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8627 goto onError;
8628 return;
8629 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008630 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008631 }
8632}
8633
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634/* error handling callback helper:
8635 build arguments, call the callback and check the arguments,
8636 put the result into newpos and return the replacement string, which
8637 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008638static PyObject *
8639unicode_translate_call_errorhandler(const char *errors,
8640 PyObject **errorHandler,
8641 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008643 Py_ssize_t startpos, Py_ssize_t endpos,
8644 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008645{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008646 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008647
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008648 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 PyObject *restuple;
8650 PyObject *resunicode;
8651
8652 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008656 }
8657
8658 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008661 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008662
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008663 restuple = PyObject_CallFunctionObjArgs(
8664 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008666 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008667 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008668 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 Py_DECREF(restuple);
8670 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008671 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008672 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 &resunicode, &i_newpos)) {
8674 Py_DECREF(restuple);
8675 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008677 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008679 else
8680 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008681 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008682 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 Py_DECREF(restuple);
8684 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008685 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 Py_INCREF(resunicode);
8687 Py_DECREF(restuple);
8688 return resunicode;
8689}
8690
8691/* Lookup the character ch in the mapping and put the result in result,
8692 which must be decrefed by the caller.
8693 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008694static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696{
Christian Heimes217cfd12007-12-02 14:31:20 +00008697 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008698 PyObject *x;
8699
8700 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008702 x = PyObject_GetItem(mapping, w);
8703 Py_DECREF(w);
8704 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8706 /* No mapping found means: use 1:1 mapping. */
8707 PyErr_Clear();
8708 *result = NULL;
8709 return 0;
8710 } else
8711 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008712 }
8713 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 *result = x;
8715 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008717 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008719 if (value < 0 || value > MAX_UNICODE) {
8720 PyErr_Format(PyExc_ValueError,
8721 "character mapping must be in range(0x%x)",
8722 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 Py_DECREF(x);
8724 return -1;
8725 }
8726 *result = x;
8727 return 0;
8728 }
8729 else if (PyUnicode_Check(x)) {
8730 *result = x;
8731 return 0;
8732 }
8733 else {
8734 /* wrong return value */
8735 PyErr_SetString(PyExc_TypeError,
8736 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008737 Py_DECREF(x);
8738 return -1;
8739 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008740}
Victor Stinner1194ea02014-04-04 19:37:40 +02008741
8742/* lookup the character, write the result into the writer.
8743 Return 1 if the result was written into the writer, return 0 if the mapping
8744 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008745static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008746charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8747 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008748{
Victor Stinner1194ea02014-04-04 19:37:40 +02008749 PyObject *item;
8750
8751 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008752 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008753
8754 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008756 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008757 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008758 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008759 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008760 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008761
8762 if (item == Py_None) {
8763 Py_DECREF(item);
8764 return 0;
8765 }
8766
8767 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008768 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8769 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8770 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008771 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8772 Py_DECREF(item);
8773 return -1;
8774 }
8775 Py_DECREF(item);
8776 return 1;
8777 }
8778
8779 if (!PyUnicode_Check(item)) {
8780 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008782 }
8783
8784 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8785 Py_DECREF(item);
8786 return -1;
8787 }
8788
8789 Py_DECREF(item);
8790 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008791}
8792
Victor Stinner89a76ab2014-04-05 11:44:04 +02008793static int
8794unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8795 Py_UCS1 *translate)
8796{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008797 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008798 int ret = 0;
8799
Victor Stinner89a76ab2014-04-05 11:44:04 +02008800 if (charmaptranslate_lookup(ch, mapping, &item)) {
8801 return -1;
8802 }
8803
8804 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008805 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008806 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008807 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008808 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008809 /* not found => default to 1:1 mapping */
8810 translate[ch] = ch;
8811 return 1;
8812 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008813 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008814 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008815 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8816 used it */
8817 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008818 /* invalid character or character outside ASCII:
8819 skip the fast translate */
8820 goto exit;
8821 }
8822 translate[ch] = (Py_UCS1)replace;
8823 }
8824 else if (PyUnicode_Check(item)) {
8825 Py_UCS4 replace;
8826
8827 if (PyUnicode_READY(item) == -1) {
8828 Py_DECREF(item);
8829 return -1;
8830 }
8831 if (PyUnicode_GET_LENGTH(item) != 1)
8832 goto exit;
8833
8834 replace = PyUnicode_READ_CHAR(item, 0);
8835 if (replace > 127)
8836 goto exit;
8837 translate[ch] = (Py_UCS1)replace;
8838 }
8839 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008840 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008841 goto exit;
8842 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008843 ret = 1;
8844
Benjamin Peterson1365de72014-04-07 20:15:41 -04008845 exit:
8846 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008847 return ret;
8848}
8849
8850/* Fast path for ascii => ascii translation. Return 1 if the whole string
8851 was translated into writer, return 0 if the input string was partially
8852 translated into writer, raise an exception and return -1 on error. */
8853static int
8854unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008855 _PyUnicodeWriter *writer, int ignore,
8856 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008857{
Victor Stinner872b2912014-04-05 14:27:07 +02008858 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859 Py_ssize_t len;
8860 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008861 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008862
Victor Stinner89a76ab2014-04-05 11:44:04 +02008863 len = PyUnicode_GET_LENGTH(input);
8864
Victor Stinner872b2912014-04-05 14:27:07 +02008865 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008866
8867 in = PyUnicode_1BYTE_DATA(input);
8868 end = in + len;
8869
8870 assert(PyUnicode_IS_ASCII(writer->buffer));
8871 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8872 out = PyUnicode_1BYTE_DATA(writer->buffer);
8873
Victor Stinner872b2912014-04-05 14:27:07 +02008874 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008875 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008876 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008877 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008878 int translate = unicode_fast_translate_lookup(mapping, ch,
8879 ascii_table);
8880 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008881 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008882 if (translate == 0)
8883 goto exit;
8884 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008885 }
Victor Stinner872b2912014-04-05 14:27:07 +02008886 if (ch2 == 0xfe) {
8887 if (ignore)
8888 continue;
8889 goto exit;
8890 }
8891 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008892 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008893 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008894 }
Victor Stinner872b2912014-04-05 14:27:07 +02008895 res = 1;
8896
8897exit:
8898 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008899 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008900 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008901}
8902
Victor Stinner3222da22015-10-01 22:07:32 +02008903static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008904_PyUnicode_TranslateCharmap(PyObject *input,
8905 PyObject *mapping,
8906 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008908 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008909 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008910 Py_ssize_t size, i;
8911 int kind;
8912 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008913 _PyUnicodeWriter writer;
8914 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008915 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008916 PyObject *errorHandler = NULL;
8917 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008918 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008919 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008920
Guido van Rossumd57fd912000-03-10 22:53:23 +00008921 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008922 PyErr_BadArgument();
8923 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008924 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008926 if (PyUnicode_READY(input) == -1)
8927 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008928 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008929 kind = PyUnicode_KIND(input);
8930 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008931
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008932 if (size == 0)
8933 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008934
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008935 /* allocate enough for a simple 1:1 translation without
8936 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008937 _PyUnicodeWriter_Init(&writer);
8938 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008939 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008940
Victor Stinner872b2912014-04-05 14:27:07 +02008941 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8942
Victor Stinner33798672016-03-01 21:59:58 +01008943 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008944 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008945 if (PyUnicode_IS_ASCII(input)) {
8946 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8947 if (res < 0) {
8948 _PyUnicodeWriter_Dealloc(&writer);
8949 return NULL;
8950 }
8951 if (res == 1)
8952 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008953 }
Victor Stinner33798672016-03-01 21:59:58 +01008954 else {
8955 i = 0;
8956 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008959 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008960 int translate;
8961 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8962 Py_ssize_t newpos;
8963 /* startpos for collecting untranslatable chars */
8964 Py_ssize_t collstart;
8965 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008966 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008967
Victor Stinner1194ea02014-04-04 19:37:40 +02008968 ch = PyUnicode_READ(kind, data, i);
8969 translate = charmaptranslate_output(ch, mapping, &writer);
8970 if (translate < 0)
8971 goto onError;
8972
8973 if (translate != 0) {
8974 /* it worked => adjust input pointer */
8975 ++i;
8976 continue;
8977 }
8978
8979 /* untranslatable character */
8980 collstart = i;
8981 collend = i+1;
8982
8983 /* find all untranslatable characters */
8984 while (collend < size) {
8985 PyObject *x;
8986 ch = PyUnicode_READ(kind, data, collend);
8987 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008988 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008989 Py_XDECREF(x);
8990 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008991 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008992 ++collend;
8993 }
8994
8995 if (ignore) {
8996 i = collend;
8997 }
8998 else {
8999 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9000 reason, input, &exc,
9001 collstart, collend, &newpos);
9002 if (repunicode == NULL)
9003 goto onError;
9004 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009005 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009006 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009007 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009008 Py_DECREF(repunicode);
9009 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009010 }
9011 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009012 Py_XDECREF(exc);
9013 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009014 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009015
Benjamin Peterson29060642009-01-31 22:14:21 +00009016 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009017 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009018 Py_XDECREF(exc);
9019 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009020 return NULL;
9021}
9022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009023/* Deprecated. Use PyUnicode_Translate instead. */
9024PyObject *
9025PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9026 Py_ssize_t size,
9027 PyObject *mapping,
9028 const char *errors)
9029{
Christian Heimes5f520f42012-09-11 14:03:25 +02009030 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009031 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009032 if (!unicode)
9033 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009034 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9035 Py_DECREF(unicode);
9036 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009037}
9038
Alexander Belopolsky40018472011-02-26 01:02:56 +00009039PyObject *
9040PyUnicode_Translate(PyObject *str,
9041 PyObject *mapping,
9042 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009043{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009044 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009045 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009046 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009047}
Tim Petersced69f82003-09-16 20:30:58 +00009048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049PyObject *
9050_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9051{
9052 if (!PyUnicode_Check(unicode)) {
9053 PyErr_BadInternalCall();
9054 return NULL;
9055 }
9056 if (PyUnicode_READY(unicode) == -1)
9057 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009058 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059 /* If the string is already ASCII, just return the same string */
9060 Py_INCREF(unicode);
9061 return unicode;
9062 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009063
9064 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9065 PyObject *result = PyUnicode_New(len, 127);
9066 if (result == NULL) {
9067 return NULL;
9068 }
9069
9070 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9071 int kind = PyUnicode_KIND(unicode);
9072 const void *data = PyUnicode_DATA(unicode);
9073 Py_ssize_t i;
9074 for (i = 0; i < len; ++i) {
9075 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9076 if (ch < 127) {
9077 out[i] = ch;
9078 }
9079 else if (Py_UNICODE_ISSPACE(ch)) {
9080 out[i] = ' ';
9081 }
9082 else {
9083 int decimal = Py_UNICODE_TODECIMAL(ch);
9084 if (decimal < 0) {
9085 out[i] = '?';
9086 _PyUnicode_LENGTH(result) = i + 1;
9087 break;
9088 }
9089 out[i] = '0' + decimal;
9090 }
9091 }
9092
9093 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009094}
9095
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009096PyObject *
9097PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9098 Py_ssize_t length)
9099{
Victor Stinnerf0124502011-11-21 23:12:56 +01009100 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009101 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009102 Py_UCS4 maxchar;
9103 enum PyUnicode_Kind kind;
9104 void *data;
9105
Victor Stinner99d7ad02012-02-22 13:37:39 +01009106 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009107 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009108 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009109 if (ch > 127) {
9110 int decimal = Py_UNICODE_TODECIMAL(ch);
9111 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009112 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009113 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009114 }
9115 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009116
9117 /* Copy to a new string */
9118 decimal = PyUnicode_New(length, maxchar);
9119 if (decimal == NULL)
9120 return decimal;
9121 kind = PyUnicode_KIND(decimal);
9122 data = PyUnicode_DATA(decimal);
9123 /* Iterate over code points */
9124 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009125 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009126 if (ch > 127) {
9127 int decimal = Py_UNICODE_TODECIMAL(ch);
9128 if (decimal >= 0)
9129 ch = '0' + decimal;
9130 }
9131 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009132 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009133 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009134}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009135/* --- Decimal Encoder ---------------------------------------------------- */
9136
Alexander Belopolsky40018472011-02-26 01:02:56 +00009137int
9138PyUnicode_EncodeDecimal(Py_UNICODE *s,
9139 Py_ssize_t length,
9140 char *output,
9141 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009142{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009143 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009144 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009145 enum PyUnicode_Kind kind;
9146 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009147
9148 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 PyErr_BadArgument();
9150 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009151 }
9152
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009153 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009154 if (unicode == NULL)
9155 return -1;
9156
Victor Stinner42bf7752011-11-21 22:52:58 +01009157 kind = PyUnicode_KIND(unicode);
9158 data = PyUnicode_DATA(unicode);
9159
Victor Stinnerb84d7232011-11-22 01:50:07 +01009160 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009161 PyObject *exc;
9162 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009163 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009164 Py_ssize_t startpos;
9165
9166 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009167
Benjamin Peterson29060642009-01-31 22:14:21 +00009168 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009169 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009170 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009171 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009172 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009173 decimal = Py_UNICODE_TODECIMAL(ch);
9174 if (decimal >= 0) {
9175 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009176 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009177 continue;
9178 }
9179 if (0 < ch && ch < 256) {
9180 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009181 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009182 continue;
9183 }
Victor Stinner6345be92011-11-25 20:09:01 +01009184
Victor Stinner42bf7752011-11-21 22:52:58 +01009185 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009186 exc = NULL;
9187 raise_encode_exception(&exc, "decimal", unicode,
9188 startpos, startpos+1,
9189 "invalid decimal Unicode string");
9190 Py_XDECREF(exc);
9191 Py_DECREF(unicode);
9192 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009193 }
9194 /* 0-terminate the output string */
9195 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009196 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009197 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009198}
9199
Guido van Rossumd57fd912000-03-10 22:53:23 +00009200/* --- Helpers ------------------------------------------------------------ */
9201
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009202/* helper macro to fixup start/end slice values */
9203#define ADJUST_INDICES(start, end, len) \
9204 if (end > len) \
9205 end = len; \
9206 else if (end < 0) { \
9207 end += len; \
9208 if (end < 0) \
9209 end = 0; \
9210 } \
9211 if (start < 0) { \
9212 start += len; \
9213 if (start < 0) \
9214 start = 0; \
9215 }
9216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009217static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009218any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009220 Py_ssize_t end,
9221 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009222{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009223 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009224 void *buf1, *buf2;
9225 Py_ssize_t len1, len2, result;
9226
9227 kind1 = PyUnicode_KIND(s1);
9228 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009229 if (kind1 < kind2)
9230 return -1;
9231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 len1 = PyUnicode_GET_LENGTH(s1);
9233 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009234 ADJUST_INDICES(start, end, len1);
9235 if (end - start < len2)
9236 return -1;
9237
9238 buf1 = PyUnicode_DATA(s1);
9239 buf2 = PyUnicode_DATA(s2);
9240 if (len2 == 1) {
9241 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9242 result = findchar((const char *)buf1 + kind1*start,
9243 kind1, end - start, ch, direction);
9244 if (result == -1)
9245 return -1;
9246 else
9247 return start + result;
9248 }
9249
9250 if (kind2 != kind1) {
9251 buf2 = _PyUnicode_AsKind(s2, kind1);
9252 if (!buf2)
9253 return -2;
9254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009255
Victor Stinner794d5672011-10-10 03:21:36 +02009256 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009257 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009258 case PyUnicode_1BYTE_KIND:
9259 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9260 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9261 else
9262 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9263 break;
9264 case PyUnicode_2BYTE_KIND:
9265 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9266 break;
9267 case PyUnicode_4BYTE_KIND:
9268 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9269 break;
9270 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009271 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009272 }
9273 }
9274 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009275 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009276 case PyUnicode_1BYTE_KIND:
9277 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9278 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9279 else
9280 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9281 break;
9282 case PyUnicode_2BYTE_KIND:
9283 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9284 break;
9285 case PyUnicode_4BYTE_KIND:
9286 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9287 break;
9288 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009289 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009291 }
9292
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009293 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 PyMem_Free(buf2);
9295
9296 return result;
9297}
9298
9299Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009300_PyUnicode_InsertThousandsGrouping(
9301 PyObject *unicode, Py_ssize_t index,
9302 Py_ssize_t n_buffer,
9303 void *digits, Py_ssize_t n_digits,
9304 Py_ssize_t min_width,
9305 const char *grouping, PyObject *thousands_sep,
9306 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009307{
Victor Stinner41a863c2012-02-24 00:37:51 +01009308 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009309 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009310 Py_ssize_t thousands_sep_len;
9311 Py_ssize_t len;
9312
9313 if (unicode != NULL) {
9314 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009315 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009316 }
9317 else {
9318 kind = PyUnicode_1BYTE_KIND;
9319 data = NULL;
9320 }
9321 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9322 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9323 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9324 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009325 if (thousands_sep_kind < kind) {
9326 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9327 if (!thousands_sep_data)
9328 return -1;
9329 }
9330 else {
9331 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9332 if (!data)
9333 return -1;
9334 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009335 }
9336
Benjamin Petersonead6b532011-12-20 17:23:42 -06009337 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009339 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009340 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009341 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009342 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009343 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009344 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009345 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009346 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009347 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009348 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009349 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009350 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009351 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009352 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009353 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009354 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009355 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009357 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009358 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009359 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009360 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009361 break;
9362 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009363 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009364 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009365 if (unicode != NULL && thousands_sep_kind != kind) {
9366 if (thousands_sep_kind < kind)
9367 PyMem_Free(thousands_sep_data);
9368 else
9369 PyMem_Free(data);
9370 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009371 if (unicode == NULL) {
9372 *maxchar = 127;
9373 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009374 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009375 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009376 }
9377 }
9378 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379}
9380
9381
Alexander Belopolsky40018472011-02-26 01:02:56 +00009382Py_ssize_t
9383PyUnicode_Count(PyObject *str,
9384 PyObject *substr,
9385 Py_ssize_t start,
9386 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009387{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009388 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009389 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 void *buf1 = NULL, *buf2 = NULL;
9391 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009392
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009393 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009394 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009395
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009396 kind1 = PyUnicode_KIND(str);
9397 kind2 = PyUnicode_KIND(substr);
9398 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009399 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009400
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009401 len1 = PyUnicode_GET_LENGTH(str);
9402 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009403 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009404 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009405 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009406
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009407 buf1 = PyUnicode_DATA(str);
9408 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009409 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009410 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009411 if (!buf2)
9412 goto onError;
9413 }
9414
9415 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009417 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009418 result = asciilib_count(
9419 ((Py_UCS1*)buf1) + start, end - start,
9420 buf2, len2, PY_SSIZE_T_MAX
9421 );
9422 else
9423 result = ucs1lib_count(
9424 ((Py_UCS1*)buf1) + start, end - start,
9425 buf2, len2, PY_SSIZE_T_MAX
9426 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427 break;
9428 case PyUnicode_2BYTE_KIND:
9429 result = ucs2lib_count(
9430 ((Py_UCS2*)buf1) + start, end - start,
9431 buf2, len2, PY_SSIZE_T_MAX
9432 );
9433 break;
9434 case PyUnicode_4BYTE_KIND:
9435 result = ucs4lib_count(
9436 ((Py_UCS4*)buf1) + start, end - start,
9437 buf2, len2, PY_SSIZE_T_MAX
9438 );
9439 break;
9440 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009441 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009443
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009444 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445 PyMem_Free(buf2);
9446
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009448 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009449 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 PyMem_Free(buf2);
9451 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009452}
9453
Alexander Belopolsky40018472011-02-26 01:02:56 +00009454Py_ssize_t
9455PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009456 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009457 Py_ssize_t start,
9458 Py_ssize_t end,
9459 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009460{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009461 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009462 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009463
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009464 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009465}
9466
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467Py_ssize_t
9468PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9469 Py_ssize_t start, Py_ssize_t end,
9470 int direction)
9471{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009473 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474 if (PyUnicode_READY(str) == -1)
9475 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009476 len = PyUnicode_GET_LENGTH(str);
9477 ADJUST_INDICES(start, end, len);
9478 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009479 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009481 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9482 kind, end-start, ch, direction);
9483 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009485 else
9486 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487}
9488
Alexander Belopolsky40018472011-02-26 01:02:56 +00009489static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009490tailmatch(PyObject *self,
9491 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009492 Py_ssize_t start,
9493 Py_ssize_t end,
9494 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009496 int kind_self;
9497 int kind_sub;
9498 void *data_self;
9499 void *data_sub;
9500 Py_ssize_t offset;
9501 Py_ssize_t i;
9502 Py_ssize_t end_sub;
9503
9504 if (PyUnicode_READY(self) == -1 ||
9505 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009506 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009507
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9509 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009511 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009512
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009513 if (PyUnicode_GET_LENGTH(substring) == 0)
9514 return 1;
9515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 kind_self = PyUnicode_KIND(self);
9517 data_self = PyUnicode_DATA(self);
9518 kind_sub = PyUnicode_KIND(substring);
9519 data_sub = PyUnicode_DATA(substring);
9520 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9521
9522 if (direction > 0)
9523 offset = end;
9524 else
9525 offset = start;
9526
9527 if (PyUnicode_READ(kind_self, data_self, offset) ==
9528 PyUnicode_READ(kind_sub, data_sub, 0) &&
9529 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9530 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9531 /* If both are of the same kind, memcmp is sufficient */
9532 if (kind_self == kind_sub) {
9533 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009534 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 data_sub,
9536 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009537 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009538 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009539 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009540 else {
9541 /* We do not need to compare 0 and len(substring)-1 because
9542 the if statement above ensured already that they are equal
9543 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 for (i = 1; i < end_sub; ++i) {
9545 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9546 PyUnicode_READ(kind_sub, data_sub, i))
9547 return 0;
9548 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009549 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551 }
9552
9553 return 0;
9554}
9555
Alexander Belopolsky40018472011-02-26 01:02:56 +00009556Py_ssize_t
9557PyUnicode_Tailmatch(PyObject *str,
9558 PyObject *substr,
9559 Py_ssize_t start,
9560 Py_ssize_t end,
9561 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009562{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009563 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009564 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009565
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009566 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567}
9568
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009569static PyObject *
9570ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009572 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9573 char *resdata, *data = PyUnicode_DATA(self);
9574 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009575
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009576 res = PyUnicode_New(len, 127);
9577 if (res == NULL)
9578 return NULL;
9579 resdata = PyUnicode_DATA(res);
9580 if (lower)
9581 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009583 _Py_bytes_upper(resdata, data, len);
9584 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009585}
9586
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009588handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009589{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009590 Py_ssize_t j;
9591 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009592 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009593 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009594
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009595 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9596
9597 where ! is a negation and \p{xxx} is a character with property xxx.
9598 */
9599 for (j = i - 1; j >= 0; j--) {
9600 c = PyUnicode_READ(kind, data, j);
9601 if (!_PyUnicode_IsCaseIgnorable(c))
9602 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009603 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009604 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9605 if (final_sigma) {
9606 for (j = i + 1; j < length; j++) {
9607 c = PyUnicode_READ(kind, data, j);
9608 if (!_PyUnicode_IsCaseIgnorable(c))
9609 break;
9610 }
9611 final_sigma = j == length || !_PyUnicode_IsCased(c);
9612 }
9613 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009614}
9615
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009616static int
9617lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9618 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009619{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009620 /* Obscure special case. */
9621 if (c == 0x3A3) {
9622 mapped[0] = handle_capital_sigma(kind, data, length, i);
9623 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009624 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009625 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626}
9627
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009628static Py_ssize_t
9629do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009630{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009631 Py_ssize_t i, k = 0;
9632 int n_res, j;
9633 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009634
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635 c = PyUnicode_READ(kind, data, 0);
9636 n_res = _PyUnicode_ToUpperFull(c, mapped);
9637 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009638 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009639 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009640 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009641 for (i = 1; i < length; i++) {
9642 c = PyUnicode_READ(kind, data, i);
9643 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9644 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009645 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009646 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009647 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009648 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650}
9651
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009652static Py_ssize_t
9653do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9654 Py_ssize_t i, k = 0;
9655
9656 for (i = 0; i < length; i++) {
9657 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9658 int n_res, j;
9659 if (Py_UNICODE_ISUPPER(c)) {
9660 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9661 }
9662 else if (Py_UNICODE_ISLOWER(c)) {
9663 n_res = _PyUnicode_ToUpperFull(c, mapped);
9664 }
9665 else {
9666 n_res = 1;
9667 mapped[0] = c;
9668 }
9669 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009670 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009671 res[k++] = mapped[j];
9672 }
9673 }
9674 return k;
9675}
9676
9677static Py_ssize_t
9678do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9679 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009680{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681 Py_ssize_t i, k = 0;
9682
9683 for (i = 0; i < length; i++) {
9684 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9685 int n_res, j;
9686 if (lower)
9687 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9688 else
9689 n_res = _PyUnicode_ToUpperFull(c, mapped);
9690 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009691 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009692 res[k++] = mapped[j];
9693 }
9694 }
9695 return k;
9696}
9697
9698static Py_ssize_t
9699do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9700{
9701 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9702}
9703
9704static Py_ssize_t
9705do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9706{
9707 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9708}
9709
Benjamin Petersone51757f2012-01-12 21:10:29 -05009710static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009711do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9712{
9713 Py_ssize_t i, k = 0;
9714
9715 for (i = 0; i < length; i++) {
9716 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9717 Py_UCS4 mapped[3];
9718 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9719 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009720 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009721 res[k++] = mapped[j];
9722 }
9723 }
9724 return k;
9725}
9726
9727static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009728do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9729{
9730 Py_ssize_t i, k = 0;
9731 int previous_is_cased;
9732
9733 previous_is_cased = 0;
9734 for (i = 0; i < length; i++) {
9735 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9736 Py_UCS4 mapped[3];
9737 int n_res, j;
9738
9739 if (previous_is_cased)
9740 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9741 else
9742 n_res = _PyUnicode_ToTitleFull(c, mapped);
9743
9744 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009745 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009746 res[k++] = mapped[j];
9747 }
9748
9749 previous_is_cased = _PyUnicode_IsCased(c);
9750 }
9751 return k;
9752}
9753
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009754static PyObject *
9755case_operation(PyObject *self,
9756 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9757{
9758 PyObject *res = NULL;
9759 Py_ssize_t length, newlength = 0;
9760 int kind, outkind;
9761 void *data, *outdata;
9762 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9763
Benjamin Petersoneea48462012-01-16 14:28:50 -05009764 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009765
9766 kind = PyUnicode_KIND(self);
9767 data = PyUnicode_DATA(self);
9768 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009769 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009770 PyErr_SetString(PyExc_OverflowError, "string is too long");
9771 return NULL;
9772 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009773 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009774 if (tmp == NULL)
9775 return PyErr_NoMemory();
9776 newlength = perform(kind, data, length, tmp, &maxchar);
9777 res = PyUnicode_New(newlength, maxchar);
9778 if (res == NULL)
9779 goto leave;
9780 tmpend = tmp + newlength;
9781 outdata = PyUnicode_DATA(res);
9782 outkind = PyUnicode_KIND(res);
9783 switch (outkind) {
9784 case PyUnicode_1BYTE_KIND:
9785 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9786 break;
9787 case PyUnicode_2BYTE_KIND:
9788 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9789 break;
9790 case PyUnicode_4BYTE_KIND:
9791 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9792 break;
9793 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009794 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009795 }
9796 leave:
9797 PyMem_FREE(tmp);
9798 return res;
9799}
9800
Tim Peters8ce9f162004-08-27 01:49:32 +00009801PyObject *
9802PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009804 PyObject *res;
9805 PyObject *fseq;
9806 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009807 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009808
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009809 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009810 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009811 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009812 }
9813
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009814 /* NOTE: the following code can't call back into Python code,
9815 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009816 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009817
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009818 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009819 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009820 res = _PyUnicode_JoinArray(separator, items, seqlen);
9821 Py_DECREF(fseq);
9822 return res;
9823}
9824
9825PyObject *
9826_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9827{
9828 PyObject *res = NULL; /* the result */
9829 PyObject *sep = NULL;
9830 Py_ssize_t seplen;
9831 PyObject *item;
9832 Py_ssize_t sz, i, res_offset;
9833 Py_UCS4 maxchar;
9834 Py_UCS4 item_maxchar;
9835 int use_memcpy;
9836 unsigned char *res_data = NULL, *sep_data = NULL;
9837 PyObject *last_obj;
9838 unsigned int kind = 0;
9839
Tim Peters05eba1f2004-08-27 21:32:02 +00009840 /* If empty sequence, return u"". */
9841 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009842 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009843 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009844
Tim Peters05eba1f2004-08-27 21:32:02 +00009845 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009846 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009847 if (seqlen == 1) {
9848 if (PyUnicode_CheckExact(items[0])) {
9849 res = items[0];
9850 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009851 return res;
9852 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009853 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009854 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009855 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009856 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009857 /* Set up sep and seplen */
9858 if (separator == NULL) {
9859 /* fall back to a blank space separator */
9860 sep = PyUnicode_FromOrdinal(' ');
9861 if (!sep)
9862 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009863 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009864 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009865 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009866 else {
9867 if (!PyUnicode_Check(separator)) {
9868 PyErr_Format(PyExc_TypeError,
9869 "separator: expected str instance,"
9870 " %.80s found",
9871 Py_TYPE(separator)->tp_name);
9872 goto onError;
9873 }
9874 if (PyUnicode_READY(separator))
9875 goto onError;
9876 sep = separator;
9877 seplen = PyUnicode_GET_LENGTH(separator);
9878 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9879 /* inc refcount to keep this code path symmetric with the
9880 above case of a blank separator */
9881 Py_INCREF(sep);
9882 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009883 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009884 }
9885
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009886 /* There are at least two things to join, or else we have a subclass
9887 * of str in the sequence.
9888 * Do a pre-pass to figure out the total amount of space we'll
9889 * need (sz), and see whether all argument are strings.
9890 */
9891 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009892#ifdef Py_DEBUG
9893 use_memcpy = 0;
9894#else
9895 use_memcpy = 1;
9896#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009897 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009898 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009899 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009900 if (!PyUnicode_Check(item)) {
9901 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009902 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009903 " %.80s found",
9904 i, Py_TYPE(item)->tp_name);
9905 goto onError;
9906 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009907 if (PyUnicode_READY(item) == -1)
9908 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009909 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009910 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009911 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009912 if (i != 0) {
9913 add_sz += seplen;
9914 }
9915 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009916 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009917 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009918 goto onError;
9919 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009920 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009921 if (use_memcpy && last_obj != NULL) {
9922 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9923 use_memcpy = 0;
9924 }
9925 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009926 }
Tim Petersced69f82003-09-16 20:30:58 +00009927
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009929 if (res == NULL)
9930 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009931
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009932 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009933#ifdef Py_DEBUG
9934 use_memcpy = 0;
9935#else
9936 if (use_memcpy) {
9937 res_data = PyUnicode_1BYTE_DATA(res);
9938 kind = PyUnicode_KIND(res);
9939 if (seplen != 0)
9940 sep_data = PyUnicode_1BYTE_DATA(sep);
9941 }
9942#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009943 if (use_memcpy) {
9944 for (i = 0; i < seqlen; ++i) {
9945 Py_ssize_t itemlen;
9946 item = items[i];
9947
9948 /* Copy item, and maybe the separator. */
9949 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009950 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009951 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009952 kind * seplen);
9953 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009954 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009955
9956 itemlen = PyUnicode_GET_LENGTH(item);
9957 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009958 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009959 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009960 kind * itemlen);
9961 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009962 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009963 }
9964 assert(res_data == PyUnicode_1BYTE_DATA(res)
9965 + kind * PyUnicode_GET_LENGTH(res));
9966 }
9967 else {
9968 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9969 Py_ssize_t itemlen;
9970 item = items[i];
9971
9972 /* Copy item, and maybe the separator. */
9973 if (i && seplen != 0) {
9974 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9975 res_offset += seplen;
9976 }
9977
9978 itemlen = PyUnicode_GET_LENGTH(item);
9979 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009980 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009981 res_offset += itemlen;
9982 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009983 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009984 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009985 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009988 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990
Benjamin Peterson29060642009-01-31 22:14:21 +00009991 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009992 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009993 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009994 return NULL;
9995}
9996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997#define FILL(kind, data, value, start, length) \
9998 do { \
9999 Py_ssize_t i_ = 0; \
10000 assert(kind != PyUnicode_WCHAR_KIND); \
10001 switch ((kind)) { \
10002 case PyUnicode_1BYTE_KIND: { \
10003 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010004 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005 break; \
10006 } \
10007 case PyUnicode_2BYTE_KIND: { \
10008 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10009 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10010 break; \
10011 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010012 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10014 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10015 break; \
10016 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010017 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010018 } \
10019 } while (0)
10020
Victor Stinnerd3f08822012-05-29 12:57:52 +020010021void
10022_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10023 Py_UCS4 fill_char)
10024{
10025 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10026 const void *data = PyUnicode_DATA(unicode);
10027 assert(PyUnicode_IS_READY(unicode));
10028 assert(unicode_modifiable(unicode));
10029 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10030 assert(start >= 0);
10031 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10032 FILL(kind, data, fill_char, start, length);
10033}
10034
Victor Stinner3fe55312012-01-04 00:33:50 +010010035Py_ssize_t
10036PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10037 Py_UCS4 fill_char)
10038{
10039 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010040
10041 if (!PyUnicode_Check(unicode)) {
10042 PyErr_BadInternalCall();
10043 return -1;
10044 }
10045 if (PyUnicode_READY(unicode) == -1)
10046 return -1;
10047 if (unicode_check_modifiable(unicode))
10048 return -1;
10049
Victor Stinnerd3f08822012-05-29 12:57:52 +020010050 if (start < 0) {
10051 PyErr_SetString(PyExc_IndexError, "string index out of range");
10052 return -1;
10053 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010054 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10055 PyErr_SetString(PyExc_ValueError,
10056 "fill character is bigger than "
10057 "the string maximum character");
10058 return -1;
10059 }
10060
10061 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10062 length = Py_MIN(maxlen, length);
10063 if (length <= 0)
10064 return 0;
10065
Victor Stinnerd3f08822012-05-29 12:57:52 +020010066 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010067 return length;
10068}
10069
Victor Stinner9310abb2011-10-05 00:59:23 +020010070static PyObject *
10071pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010072 Py_ssize_t left,
10073 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010075{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 PyObject *u;
10077 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010078 int kind;
10079 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010080
10081 if (left < 0)
10082 left = 0;
10083 if (right < 0)
10084 right = 0;
10085
Victor Stinnerc4b49542011-12-11 22:44:26 +010010086 if (left == 0 && right == 0)
10087 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10090 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010091 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10092 return NULL;
10093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010095 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010097 if (!u)
10098 return NULL;
10099
10100 kind = PyUnicode_KIND(u);
10101 data = PyUnicode_DATA(u);
10102 if (left)
10103 FILL(kind, data, fill, 0, left);
10104 if (right)
10105 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010106 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010107 assert(_PyUnicode_CheckConsistency(u, 1));
10108 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109}
10110
Alexander Belopolsky40018472011-02-26 01:02:56 +000010111PyObject *
10112PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010113{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010114 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010115
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010116 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010117 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010118
Benjamin Petersonead6b532011-12-20 17:23:42 -060010119 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010121 if (PyUnicode_IS_ASCII(string))
10122 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010123 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010124 PyUnicode_GET_LENGTH(string), keepends);
10125 else
10126 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010127 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010128 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 break;
10130 case PyUnicode_2BYTE_KIND:
10131 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010132 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 PyUnicode_GET_LENGTH(string), keepends);
10134 break;
10135 case PyUnicode_4BYTE_KIND:
10136 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010137 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 PyUnicode_GET_LENGTH(string), keepends);
10139 break;
10140 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010141 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010143 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010144}
10145
Alexander Belopolsky40018472011-02-26 01:02:56 +000010146static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010147split(PyObject *self,
10148 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010149 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010150{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010151 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 void *buf1, *buf2;
10153 Py_ssize_t len1, len2;
10154 PyObject* out;
10155
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010157 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 if (PyUnicode_READY(self) == -1)
10160 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010161
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010163 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010165 if (PyUnicode_IS_ASCII(self))
10166 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010167 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010168 PyUnicode_GET_LENGTH(self), maxcount
10169 );
10170 else
10171 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010172 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010173 PyUnicode_GET_LENGTH(self), maxcount
10174 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 case PyUnicode_2BYTE_KIND:
10176 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010177 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 PyUnicode_GET_LENGTH(self), maxcount
10179 );
10180 case PyUnicode_4BYTE_KIND:
10181 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010182 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 PyUnicode_GET_LENGTH(self), maxcount
10184 );
10185 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010186 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187 }
10188
10189 if (PyUnicode_READY(substring) == -1)
10190 return NULL;
10191
10192 kind1 = PyUnicode_KIND(self);
10193 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 len1 = PyUnicode_GET_LENGTH(self);
10195 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010196 if (kind1 < kind2 || len1 < len2) {
10197 out = PyList_New(1);
10198 if (out == NULL)
10199 return NULL;
10200 Py_INCREF(self);
10201 PyList_SET_ITEM(out, 0, self);
10202 return out;
10203 }
10204 buf1 = PyUnicode_DATA(self);
10205 buf2 = PyUnicode_DATA(substring);
10206 if (kind2 != kind1) {
10207 buf2 = _PyUnicode_AsKind(substring, kind1);
10208 if (!buf2)
10209 return NULL;
10210 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010212 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010214 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10215 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010216 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010217 else
10218 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010219 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 break;
10221 case PyUnicode_2BYTE_KIND:
10222 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010223 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 break;
10225 case PyUnicode_4BYTE_KIND:
10226 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010227 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 break;
10229 default:
10230 out = NULL;
10231 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010232 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 PyMem_Free(buf2);
10234 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010235}
10236
Alexander Belopolsky40018472011-02-26 01:02:56 +000010237static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010238rsplit(PyObject *self,
10239 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010240 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010241{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010242 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 void *buf1, *buf2;
10244 Py_ssize_t len1, len2;
10245 PyObject* out;
10246
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010247 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010248 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010249
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 if (PyUnicode_READY(self) == -1)
10251 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010254 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010256 if (PyUnicode_IS_ASCII(self))
10257 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010258 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010259 PyUnicode_GET_LENGTH(self), maxcount
10260 );
10261 else
10262 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010263 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010264 PyUnicode_GET_LENGTH(self), maxcount
10265 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 case PyUnicode_2BYTE_KIND:
10267 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010268 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 PyUnicode_GET_LENGTH(self), maxcount
10270 );
10271 case PyUnicode_4BYTE_KIND:
10272 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010273 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 PyUnicode_GET_LENGTH(self), maxcount
10275 );
10276 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010277 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 }
10279
10280 if (PyUnicode_READY(substring) == -1)
10281 return NULL;
10282
10283 kind1 = PyUnicode_KIND(self);
10284 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 len1 = PyUnicode_GET_LENGTH(self);
10286 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010287 if (kind1 < kind2 || len1 < len2) {
10288 out = PyList_New(1);
10289 if (out == NULL)
10290 return NULL;
10291 Py_INCREF(self);
10292 PyList_SET_ITEM(out, 0, self);
10293 return out;
10294 }
10295 buf1 = PyUnicode_DATA(self);
10296 buf2 = PyUnicode_DATA(substring);
10297 if (kind2 != kind1) {
10298 buf2 = _PyUnicode_AsKind(substring, kind1);
10299 if (!buf2)
10300 return NULL;
10301 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010303 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010305 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10306 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010307 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010308 else
10309 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010310 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 break;
10312 case PyUnicode_2BYTE_KIND:
10313 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010314 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 break;
10316 case PyUnicode_4BYTE_KIND:
10317 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010318 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 break;
10320 default:
10321 out = NULL;
10322 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010323 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 PyMem_Free(buf2);
10325 return out;
10326}
10327
10328static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010329anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10330 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010332 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010334 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10335 return asciilib_find(buf1, len1, buf2, len2, offset);
10336 else
10337 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 case PyUnicode_2BYTE_KIND:
10339 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10340 case PyUnicode_4BYTE_KIND:
10341 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10342 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010343 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344}
10345
10346static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010347anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10348 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010350 switch (kind) {
10351 case PyUnicode_1BYTE_KIND:
10352 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10353 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10354 else
10355 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10356 case PyUnicode_2BYTE_KIND:
10357 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10358 case PyUnicode_4BYTE_KIND:
10359 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10360 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010361 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010362}
10363
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010364static void
10365replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10366 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10367{
10368 int kind = PyUnicode_KIND(u);
10369 void *data = PyUnicode_DATA(u);
10370 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10371 if (kind == PyUnicode_1BYTE_KIND) {
10372 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10373 (Py_UCS1 *)data + len,
10374 u1, u2, maxcount);
10375 }
10376 else if (kind == PyUnicode_2BYTE_KIND) {
10377 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10378 (Py_UCS2 *)data + len,
10379 u1, u2, maxcount);
10380 }
10381 else {
10382 assert(kind == PyUnicode_4BYTE_KIND);
10383 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10384 (Py_UCS4 *)data + len,
10385 u1, u2, maxcount);
10386 }
10387}
10388
Alexander Belopolsky40018472011-02-26 01:02:56 +000010389static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390replace(PyObject *self, PyObject *str1,
10391 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 PyObject *u;
10394 char *sbuf = PyUnicode_DATA(self);
10395 char *buf1 = PyUnicode_DATA(str1);
10396 char *buf2 = PyUnicode_DATA(str2);
10397 int srelease = 0, release1 = 0, release2 = 0;
10398 int skind = PyUnicode_KIND(self);
10399 int kind1 = PyUnicode_KIND(str1);
10400 int kind2 = PyUnicode_KIND(str2);
10401 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10402 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10403 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010404 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010405 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010406
10407 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010408 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010410 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010411
Victor Stinner59de0ee2011-10-07 10:01:28 +020010412 if (str1 == str2)
10413 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414
Victor Stinner49a0a212011-10-12 23:46:10 +020010415 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010416 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10417 if (maxchar < maxchar_str1)
10418 /* substring too wide to be present */
10419 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010420 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10421 /* Replacing str1 with str2 may cause a maxchar reduction in the
10422 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010423 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010424 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010427 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010429 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010431 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010432 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010433 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010434
Victor Stinner69ed0f42013-04-09 21:48:24 +020010435 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010436 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010437 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010438 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010439 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010441 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010443
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010444 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10445 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010446 }
10447 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 int rkind = skind;
10449 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010450 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 if (kind1 < rkind) {
10453 /* widen substring */
10454 buf1 = _PyUnicode_AsKind(str1, rkind);
10455 if (!buf1) goto error;
10456 release1 = 1;
10457 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010458 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010459 if (i < 0)
10460 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 if (rkind > kind2) {
10462 /* widen replacement */
10463 buf2 = _PyUnicode_AsKind(str2, rkind);
10464 if (!buf2) goto error;
10465 release2 = 1;
10466 }
10467 else if (rkind < kind2) {
10468 /* widen self and buf1 */
10469 rkind = kind2;
10470 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010471 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472 sbuf = _PyUnicode_AsKind(self, rkind);
10473 if (!sbuf) goto error;
10474 srelease = 1;
10475 buf1 = _PyUnicode_AsKind(str1, rkind);
10476 if (!buf1) goto error;
10477 release1 = 1;
10478 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010479 u = PyUnicode_New(slen, maxchar);
10480 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010482 assert(PyUnicode_KIND(u) == rkind);
10483 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010484
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010485 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010486 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010487 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010489 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010491
10492 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010493 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010494 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010495 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010496 if (i == -1)
10497 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010498 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010500 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010502 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010503 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010504 }
10505 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010507 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508 int rkind = skind;
10509 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010512 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 buf1 = _PyUnicode_AsKind(str1, rkind);
10514 if (!buf1) goto error;
10515 release1 = 1;
10516 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010517 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010518 if (n == 0)
10519 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010521 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 buf2 = _PyUnicode_AsKind(str2, rkind);
10523 if (!buf2) goto error;
10524 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010526 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010527 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 rkind = kind2;
10529 sbuf = _PyUnicode_AsKind(self, rkind);
10530 if (!sbuf) goto error;
10531 srelease = 1;
10532 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010533 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 buf1 = _PyUnicode_AsKind(str1, rkind);
10535 if (!buf1) goto error;
10536 release1 = 1;
10537 }
10538 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10539 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010540 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 PyErr_SetString(PyExc_OverflowError,
10542 "replace string is too long");
10543 goto error;
10544 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010545 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010546 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010547 _Py_INCREF_UNICODE_EMPTY();
10548 if (!unicode_empty)
10549 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010550 u = unicode_empty;
10551 goto done;
10552 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010553 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010554 PyErr_SetString(PyExc_OverflowError,
10555 "replace string is too long");
10556 goto error;
10557 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010558 u = PyUnicode_New(new_size, maxchar);
10559 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010560 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010561 assert(PyUnicode_KIND(u) == rkind);
10562 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 ires = i = 0;
10564 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010565 while (n-- > 0) {
10566 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010567 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010568 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010569 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010570 if (j == -1)
10571 break;
10572 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010573 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010574 memcpy(res + rkind * ires,
10575 sbuf + rkind * i,
10576 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010578 }
10579 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010581 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010583 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010585 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010589 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010590 memcpy(res + rkind * ires,
10591 sbuf + rkind * i,
10592 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010593 }
10594 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010595 /* interleave */
10596 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010597 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010599 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010601 if (--n <= 0)
10602 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010603 memcpy(res + rkind * ires,
10604 sbuf + rkind * i,
10605 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 ires++;
10607 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010608 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010609 memcpy(res + rkind * ires,
10610 sbuf + rkind * i,
10611 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010612 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010613 }
10614
10615 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010616 unicode_adjust_maxchar(&u);
10617 if (u == NULL)
10618 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010620
10621 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 if (srelease)
10623 PyMem_FREE(sbuf);
10624 if (release1)
10625 PyMem_FREE(buf1);
10626 if (release2)
10627 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010628 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010630
Benjamin Peterson29060642009-01-31 22:14:21 +000010631 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010632 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 if (srelease)
10634 PyMem_FREE(sbuf);
10635 if (release1)
10636 PyMem_FREE(buf1);
10637 if (release2)
10638 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010639 return unicode_result_unchanged(self);
10640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 error:
10642 if (srelease && sbuf)
10643 PyMem_FREE(sbuf);
10644 if (release1 && buf1)
10645 PyMem_FREE(buf1);
10646 if (release2 && buf2)
10647 PyMem_FREE(buf2);
10648 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010649}
10650
10651/* --- Unicode Object Methods --------------------------------------------- */
10652
INADA Naoki3ae20562017-01-16 20:41:20 +090010653/*[clinic input]
10654str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010655
INADA Naoki3ae20562017-01-16 20:41:20 +090010656Return a version of the string where each word is titlecased.
10657
10658More specifically, words start with uppercased characters and all remaining
10659cased characters have lower case.
10660[clinic start generated code]*/
10661
10662static PyObject *
10663unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010664/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010665{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010666 if (PyUnicode_READY(self) == -1)
10667 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010668 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010669}
10670
INADA Naoki3ae20562017-01-16 20:41:20 +090010671/*[clinic input]
10672str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010673
INADA Naoki3ae20562017-01-16 20:41:20 +090010674Return a capitalized version of the string.
10675
10676More specifically, make the first character have upper case and the rest lower
10677case.
10678[clinic start generated code]*/
10679
10680static PyObject *
10681unicode_capitalize_impl(PyObject *self)
10682/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010684 if (PyUnicode_READY(self) == -1)
10685 return NULL;
10686 if (PyUnicode_GET_LENGTH(self) == 0)
10687 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010688 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689}
10690
INADA Naoki3ae20562017-01-16 20:41:20 +090010691/*[clinic input]
10692str.casefold as unicode_casefold
10693
10694Return a version of the string suitable for caseless comparisons.
10695[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010696
10697static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010698unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010699/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010700{
10701 if (PyUnicode_READY(self) == -1)
10702 return NULL;
10703 if (PyUnicode_IS_ASCII(self))
10704 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010705 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010706}
10707
10708
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010709/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010710
10711static int
10712convert_uc(PyObject *obj, void *addr)
10713{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010715
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010716 if (!PyUnicode_Check(obj)) {
10717 PyErr_Format(PyExc_TypeError,
10718 "The fill character must be a unicode character, "
10719 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010720 return 0;
10721 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010722 if (PyUnicode_READY(obj) < 0)
10723 return 0;
10724 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010725 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010726 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010727 return 0;
10728 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010729 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010730 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010731}
10732
INADA Naoki3ae20562017-01-16 20:41:20 +090010733/*[clinic input]
10734str.center as unicode_center
10735
10736 width: Py_ssize_t
10737 fillchar: Py_UCS4 = ' '
10738 /
10739
10740Return a centered string of length width.
10741
10742Padding is done using the specified fill character (default is a space).
10743[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744
10745static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010746unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10747/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010749 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750
Benjamin Petersonbac79492012-01-14 13:34:47 -050010751 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752 return NULL;
10753
Victor Stinnerc4b49542011-12-11 22:44:26 +010010754 if (PyUnicode_GET_LENGTH(self) >= width)
10755 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756
Victor Stinnerc4b49542011-12-11 22:44:26 +010010757 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758 left = marg / 2 + (marg & width & 1);
10759
Victor Stinner9310abb2011-10-05 00:59:23 +020010760 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761}
10762
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010763/* This function assumes that str1 and str2 are readied by the caller. */
10764
Marc-André Lemburge5034372000-08-08 08:04:29 +000010765static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010766unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010767{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010768#define COMPARE(TYPE1, TYPE2) \
10769 do { \
10770 TYPE1* p1 = (TYPE1 *)data1; \
10771 TYPE2* p2 = (TYPE2 *)data2; \
10772 TYPE1* end = p1 + len; \
10773 Py_UCS4 c1, c2; \
10774 for (; p1 != end; p1++, p2++) { \
10775 c1 = *p1; \
10776 c2 = *p2; \
10777 if (c1 != c2) \
10778 return (c1 < c2) ? -1 : 1; \
10779 } \
10780 } \
10781 while (0)
10782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 int kind1, kind2;
10784 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010785 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 kind1 = PyUnicode_KIND(str1);
10788 kind2 = PyUnicode_KIND(str2);
10789 data1 = PyUnicode_DATA(str1);
10790 data2 = PyUnicode_DATA(str2);
10791 len1 = PyUnicode_GET_LENGTH(str1);
10792 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010793 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010794
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010795 switch(kind1) {
10796 case PyUnicode_1BYTE_KIND:
10797 {
10798 switch(kind2) {
10799 case PyUnicode_1BYTE_KIND:
10800 {
10801 int cmp = memcmp(data1, data2, len);
10802 /* normalize result of memcmp() into the range [-1; 1] */
10803 if (cmp < 0)
10804 return -1;
10805 if (cmp > 0)
10806 return 1;
10807 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010808 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010809 case PyUnicode_2BYTE_KIND:
10810 COMPARE(Py_UCS1, Py_UCS2);
10811 break;
10812 case PyUnicode_4BYTE_KIND:
10813 COMPARE(Py_UCS1, Py_UCS4);
10814 break;
10815 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010816 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010817 }
10818 break;
10819 }
10820 case PyUnicode_2BYTE_KIND:
10821 {
10822 switch(kind2) {
10823 case PyUnicode_1BYTE_KIND:
10824 COMPARE(Py_UCS2, Py_UCS1);
10825 break;
10826 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010827 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010828 COMPARE(Py_UCS2, Py_UCS2);
10829 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010830 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010831 case PyUnicode_4BYTE_KIND:
10832 COMPARE(Py_UCS2, Py_UCS4);
10833 break;
10834 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010835 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010836 }
10837 break;
10838 }
10839 case PyUnicode_4BYTE_KIND:
10840 {
10841 switch(kind2) {
10842 case PyUnicode_1BYTE_KIND:
10843 COMPARE(Py_UCS4, Py_UCS1);
10844 break;
10845 case PyUnicode_2BYTE_KIND:
10846 COMPARE(Py_UCS4, Py_UCS2);
10847 break;
10848 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010849 {
10850#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10851 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10852 /* normalize result of wmemcmp() into the range [-1; 1] */
10853 if (cmp < 0)
10854 return -1;
10855 if (cmp > 0)
10856 return 1;
10857#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010858 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010859#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010860 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010861 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010862 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010863 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010864 }
10865 break;
10866 }
10867 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010868 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010869 }
10870
Victor Stinner770e19e2012-10-04 22:59:45 +020010871 if (len1 == len2)
10872 return 0;
10873 if (len1 < len2)
10874 return -1;
10875 else
10876 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010877
10878#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010879}
10880
Benjamin Peterson621b4302016-09-09 13:54:34 -070010881static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010882unicode_compare_eq(PyObject *str1, PyObject *str2)
10883{
10884 int kind;
10885 void *data1, *data2;
10886 Py_ssize_t len;
10887 int cmp;
10888
Victor Stinnere5567ad2012-10-23 02:48:49 +020010889 len = PyUnicode_GET_LENGTH(str1);
10890 if (PyUnicode_GET_LENGTH(str2) != len)
10891 return 0;
10892 kind = PyUnicode_KIND(str1);
10893 if (PyUnicode_KIND(str2) != kind)
10894 return 0;
10895 data1 = PyUnicode_DATA(str1);
10896 data2 = PyUnicode_DATA(str2);
10897
10898 cmp = memcmp(data1, data2, len * kind);
10899 return (cmp == 0);
10900}
10901
10902
Alexander Belopolsky40018472011-02-26 01:02:56 +000010903int
10904PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010905{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010906 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10907 if (PyUnicode_READY(left) == -1 ||
10908 PyUnicode_READY(right) == -1)
10909 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010910
10911 /* a string is equal to itself */
10912 if (left == right)
10913 return 0;
10914
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010915 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010916 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010917 PyErr_Format(PyExc_TypeError,
10918 "Can't compare %.100s and %.100s",
10919 left->ob_type->tp_name,
10920 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921 return -1;
10922}
10923
Martin v. Löwis5b222132007-06-10 09:51:05 +000010924int
10925PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10926{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927 Py_ssize_t i;
10928 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010929 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010930 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931
Victor Stinner910337b2011-10-03 03:20:16 +020010932 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010933 if (!PyUnicode_IS_READY(uni)) {
10934 const wchar_t *ws = _PyUnicode_WSTR(uni);
10935 /* Compare Unicode string and source character set string */
10936 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10937 if (chr != ustr[i])
10938 return (chr < ustr[i]) ? -1 : 1;
10939 }
10940 /* This check keeps Python strings that end in '\0' from comparing equal
10941 to C strings identical up to that point. */
10942 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10943 return 1; /* uni is longer */
10944 if (ustr[i])
10945 return -1; /* str is longer */
10946 return 0;
10947 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010948 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010949 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010950 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010951 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010952 size_t len, len2 = strlen(str);
10953 int cmp;
10954
10955 len = Py_MIN(len1, len2);
10956 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010957 if (cmp != 0) {
10958 if (cmp < 0)
10959 return -1;
10960 else
10961 return 1;
10962 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010963 if (len1 > len2)
10964 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010965 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010966 return -1; /* str is longer */
10967 return 0;
10968 }
10969 else {
10970 void *data = PyUnicode_DATA(uni);
10971 /* Compare Unicode string and source character set string */
10972 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010973 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010974 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10975 /* This check keeps Python strings that end in '\0' from comparing equal
10976 to C strings identical up to that point. */
10977 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10978 return 1; /* uni is longer */
10979 if (str[i])
10980 return -1; /* str is longer */
10981 return 0;
10982 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010983}
10984
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010985static int
10986non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
10987{
10988 size_t i, len;
10989 const wchar_t *p;
10990 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
10991 if (strlen(str) != len)
10992 return 0;
10993 p = _PyUnicode_WSTR(unicode);
10994 assert(p);
10995 for (i = 0; i < len; i++) {
10996 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020010997 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010998 return 0;
10999 }
11000 return 1;
11001}
11002
11003int
11004_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11005{
11006 size_t len;
11007 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011008 assert(str);
11009#ifndef NDEBUG
11010 for (const char *p = str; *p; p++) {
11011 assert((unsigned char)*p < 128);
11012 }
11013#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011014 if (PyUnicode_READY(unicode) == -1) {
11015 /* Memory error or bad data */
11016 PyErr_Clear();
11017 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11018 }
11019 if (!PyUnicode_IS_ASCII(unicode))
11020 return 0;
11021 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11022 return strlen(str) == len &&
11023 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11024}
11025
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011026int
11027_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11028{
11029 PyObject *right_uni;
11030 Py_hash_t hash;
11031
11032 assert(_PyUnicode_CHECK(left));
11033 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011034#ifndef NDEBUG
11035 for (const char *p = right->string; *p; p++) {
11036 assert((unsigned char)*p < 128);
11037 }
11038#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011039
11040 if (PyUnicode_READY(left) == -1) {
11041 /* memory error or bad data */
11042 PyErr_Clear();
11043 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11044 }
11045
11046 if (!PyUnicode_IS_ASCII(left))
11047 return 0;
11048
11049 right_uni = _PyUnicode_FromId(right); /* borrowed */
11050 if (right_uni == NULL) {
11051 /* memory error or bad data */
11052 PyErr_Clear();
11053 return _PyUnicode_EqualToASCIIString(left, right->string);
11054 }
11055
11056 if (left == right_uni)
11057 return 1;
11058
11059 if (PyUnicode_CHECK_INTERNED(left))
11060 return 0;
11061
11062 assert(_PyUnicode_HASH(right_uni) != 1);
11063 hash = _PyUnicode_HASH(left);
11064 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11065 return 0;
11066
11067 return unicode_compare_eq(left, right_uni);
11068}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011069
Alexander Belopolsky40018472011-02-26 01:02:56 +000011070PyObject *
11071PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011072{
11073 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011074
Victor Stinnere5567ad2012-10-23 02:48:49 +020011075 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11076 Py_RETURN_NOTIMPLEMENTED;
11077
11078 if (PyUnicode_READY(left) == -1 ||
11079 PyUnicode_READY(right) == -1)
11080 return NULL;
11081
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011082 if (left == right) {
11083 switch (op) {
11084 case Py_EQ:
11085 case Py_LE:
11086 case Py_GE:
11087 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011088 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011089 case Py_NE:
11090 case Py_LT:
11091 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011092 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011093 default:
11094 PyErr_BadArgument();
11095 return NULL;
11096 }
11097 }
11098 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011099 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011100 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011101 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011102 }
11103 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011104 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011105 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011106 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011107}
11108
Alexander Belopolsky40018472011-02-26 01:02:56 +000011109int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011110_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11111{
11112 return unicode_eq(aa, bb);
11113}
11114
11115int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011116PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011117{
Victor Stinner77282cb2013-04-14 19:22:47 +020011118 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 void *buf1, *buf2;
11120 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011121 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011122
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011123 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011124 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011125 "'in <string>' requires string as left operand, not %.100s",
11126 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011127 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011128 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011129 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011130 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011131 if (ensure_unicode(str) < 0)
11132 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011135 kind2 = PyUnicode_KIND(substr);
11136 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011137 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011139 len2 = PyUnicode_GET_LENGTH(substr);
11140 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011141 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011142 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011143 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011144 if (len2 == 1) {
11145 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11146 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011147 return result;
11148 }
11149 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011150 buf2 = _PyUnicode_AsKind(substr, kind1);
11151 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011152 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011153 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011154
Victor Stinner77282cb2013-04-14 19:22:47 +020011155 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 case PyUnicode_1BYTE_KIND:
11157 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11158 break;
11159 case PyUnicode_2BYTE_KIND:
11160 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11161 break;
11162 case PyUnicode_4BYTE_KIND:
11163 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11164 break;
11165 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011166 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011168
Victor Stinner77282cb2013-04-14 19:22:47 +020011169 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 PyMem_Free(buf2);
11171
Guido van Rossum403d68b2000-03-13 15:55:09 +000011172 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011173}
11174
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175/* Concat to string or Unicode object giving a new Unicode object. */
11176
Alexander Belopolsky40018472011-02-26 01:02:56 +000011177PyObject *
11178PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011180 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011181 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011182 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011184 if (ensure_unicode(left) < 0)
11185 return NULL;
11186
11187 if (!PyUnicode_Check(right)) {
11188 PyErr_Format(PyExc_TypeError,
11189 "can only concatenate str (not \"%.200s\") to str",
11190 right->ob_type->tp_name);
11191 return NULL;
11192 }
11193 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011194 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
11196 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011197 if (left == unicode_empty)
11198 return PyUnicode_FromObject(right);
11199 if (right == unicode_empty)
11200 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011202 left_len = PyUnicode_GET_LENGTH(left);
11203 right_len = PyUnicode_GET_LENGTH(right);
11204 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011205 PyErr_SetString(PyExc_OverflowError,
11206 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011207 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011208 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011209 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011210
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011211 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11212 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011213 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011216 result = PyUnicode_New(new_len, maxchar);
11217 if (result == NULL)
11218 return NULL;
11219 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11220 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11221 assert(_PyUnicode_CheckConsistency(result, 1));
11222 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223}
11224
Walter Dörwald1ab83302007-05-18 17:15:44 +000011225void
Victor Stinner23e56682011-10-03 03:54:37 +020011226PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011227{
Victor Stinner23e56682011-10-03 03:54:37 +020011228 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011229 Py_UCS4 maxchar, maxchar2;
11230 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011231
11232 if (p_left == NULL) {
11233 if (!PyErr_Occurred())
11234 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011235 return;
11236 }
Victor Stinner23e56682011-10-03 03:54:37 +020011237 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011238 if (right == NULL || left == NULL
11239 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011240 if (!PyErr_Occurred())
11241 PyErr_BadInternalCall();
11242 goto error;
11243 }
11244
Benjamin Petersonbac79492012-01-14 13:34:47 -050011245 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011246 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011247 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011248 goto error;
11249
Victor Stinner488fa492011-12-12 00:01:39 +010011250 /* Shortcuts */
11251 if (left == unicode_empty) {
11252 Py_DECREF(left);
11253 Py_INCREF(right);
11254 *p_left = right;
11255 return;
11256 }
11257 if (right == unicode_empty)
11258 return;
11259
11260 left_len = PyUnicode_GET_LENGTH(left);
11261 right_len = PyUnicode_GET_LENGTH(right);
11262 if (left_len > PY_SSIZE_T_MAX - right_len) {
11263 PyErr_SetString(PyExc_OverflowError,
11264 "strings are too large to concat");
11265 goto error;
11266 }
11267 new_len = left_len + right_len;
11268
11269 if (unicode_modifiable(left)
11270 && PyUnicode_CheckExact(right)
11271 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011272 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11273 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011274 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011275 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011276 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11277 {
11278 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011279 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011280 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011281
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011282 /* copy 'right' into the newly allocated area of 'left' */
11283 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011284 }
Victor Stinner488fa492011-12-12 00:01:39 +010011285 else {
11286 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11287 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011288 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011289
Victor Stinner488fa492011-12-12 00:01:39 +010011290 /* Concat the two Unicode strings */
11291 res = PyUnicode_New(new_len, maxchar);
11292 if (res == NULL)
11293 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011294 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11295 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011296 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011297 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011298 }
11299 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011300 return;
11301
11302error:
Victor Stinner488fa492011-12-12 00:01:39 +010011303 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011304}
11305
11306void
11307PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11308{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011309 PyUnicode_Append(pleft, right);
11310 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011311}
11312
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011313/*
11314Wraps stringlib_parse_args_finds() and additionally ensures that the
11315first argument is a unicode object.
11316*/
11317
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011318static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011319parse_args_finds_unicode(const char * function_name, PyObject *args,
11320 PyObject **substring,
11321 Py_ssize_t *start, Py_ssize_t *end)
11322{
11323 if(stringlib_parse_args_finds(function_name, args, substring,
11324 start, end)) {
11325 if (ensure_unicode(*substring) < 0)
11326 return 0;
11327 return 1;
11328 }
11329 return 0;
11330}
11331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011332PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011333 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011335Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011336string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011337interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338
11339static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011340unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011342 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011343 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011344 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011346 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 void *buf1, *buf2;
11348 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011350 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011351 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 kind1 = PyUnicode_KIND(self);
11354 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011355 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011356 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011357
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011358 len1 = PyUnicode_GET_LENGTH(self);
11359 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011361 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011362 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011363
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011364 buf1 = PyUnicode_DATA(self);
11365 buf2 = PyUnicode_DATA(substring);
11366 if (kind2 != kind1) {
11367 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011368 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011369 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011370 }
11371 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 case PyUnicode_1BYTE_KIND:
11373 iresult = ucs1lib_count(
11374 ((Py_UCS1*)buf1) + start, end - start,
11375 buf2, len2, PY_SSIZE_T_MAX
11376 );
11377 break;
11378 case PyUnicode_2BYTE_KIND:
11379 iresult = ucs2lib_count(
11380 ((Py_UCS2*)buf1) + start, end - start,
11381 buf2, len2, PY_SSIZE_T_MAX
11382 );
11383 break;
11384 case PyUnicode_4BYTE_KIND:
11385 iresult = ucs4lib_count(
11386 ((Py_UCS4*)buf1) + start, end - start,
11387 buf2, len2, PY_SSIZE_T_MAX
11388 );
11389 break;
11390 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011391 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 }
11393
11394 result = PyLong_FromSsize_t(iresult);
11395
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011396 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011397 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399 return result;
11400}
11401
INADA Naoki3ae20562017-01-16 20:41:20 +090011402/*[clinic input]
11403str.encode as unicode_encode
11404
11405 encoding: str(c_default="NULL") = 'utf-8'
11406 The encoding in which to encode the string.
11407 errors: str(c_default="NULL") = 'strict'
11408 The error handling scheme to use for encoding errors.
11409 The default is 'strict' meaning that encoding errors raise a
11410 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11411 'xmlcharrefreplace' as well as any other name registered with
11412 codecs.register_error that can handle UnicodeEncodeErrors.
11413
11414Encode the string using the codec registered for encoding.
11415[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
11417static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011418unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011419/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011421 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011422}
11423
INADA Naoki3ae20562017-01-16 20:41:20 +090011424/*[clinic input]
11425str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426
INADA Naoki3ae20562017-01-16 20:41:20 +090011427 tabsize: int = 8
11428
11429Return a copy where all tab characters are expanded using spaces.
11430
11431If tabsize is not given, a tab size of 8 characters is assumed.
11432[clinic start generated code]*/
11433
11434static PyObject *
11435unicode_expandtabs_impl(PyObject *self, int tabsize)
11436/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011438 Py_ssize_t i, j, line_pos, src_len, incr;
11439 Py_UCS4 ch;
11440 PyObject *u;
11441 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011442 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011443 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
Antoine Pitrou22425222011-10-04 19:10:51 +020011445 if (PyUnicode_READY(self) == -1)
11446 return NULL;
11447
Thomas Wouters7e474022000-07-16 12:04:32 +000011448 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011449 src_len = PyUnicode_GET_LENGTH(self);
11450 i = j = line_pos = 0;
11451 kind = PyUnicode_KIND(self);
11452 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011453 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011454 for (; i < src_len; i++) {
11455 ch = PyUnicode_READ(kind, src_data, i);
11456 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011457 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011458 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011459 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011460 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011461 goto overflow;
11462 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011463 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011464 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011465 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011467 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011468 goto overflow;
11469 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011471 if (ch == '\n' || ch == '\r')
11472 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011474 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011475 if (!found)
11476 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011477
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480 if (!u)
11481 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011482 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483
Antoine Pitroue71d5742011-10-04 15:55:09 +020011484 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 for (; i < src_len; i++) {
11487 ch = PyUnicode_READ(kind, src_data, i);
11488 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011490 incr = tabsize - (line_pos % tabsize);
11491 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011492 FILL(kind, dest_data, ' ', j, incr);
11493 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011494 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011495 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011496 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011497 line_pos++;
11498 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011499 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011500 if (ch == '\n' || ch == '\r')
11501 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011503 }
11504 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011505 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011506
Antoine Pitroue71d5742011-10-04 15:55:09 +020011507 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011508 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11509 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510}
11511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011512PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011513 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514\n\
11515Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011516such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517arguments start and end are interpreted as in slice notation.\n\
11518\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011519Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520
11521static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011524 /* initialize variables to prevent gcc warning */
11525 PyObject *substring = NULL;
11526 Py_ssize_t start = 0;
11527 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011528 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011530 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011533 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011536 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 if (result == -2)
11539 return NULL;
11540
Christian Heimes217cfd12007-12-02 14:31:20 +000011541 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542}
11543
11544static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011545unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011547 void *data;
11548 enum PyUnicode_Kind kind;
11549 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011550
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011551 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011552 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011554 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011555 if (PyUnicode_READY(self) == -1) {
11556 return NULL;
11557 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011558 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11559 PyErr_SetString(PyExc_IndexError, "string index out of range");
11560 return NULL;
11561 }
11562 kind = PyUnicode_KIND(self);
11563 data = PyUnicode_DATA(self);
11564 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011565 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566}
11567
Guido van Rossumc2504932007-09-18 19:42:40 +000011568/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011569 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011570static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011571unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572{
Guido van Rossumc2504932007-09-18 19:42:40 +000011573 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011574 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011575
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011576#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011577 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011578#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 if (_PyUnicode_HASH(self) != -1)
11580 return _PyUnicode_HASH(self);
11581 if (PyUnicode_READY(self) == -1)
11582 return -1;
11583 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011584 /*
11585 We make the hash of the empty string be 0, rather than using
11586 (prefix ^ suffix), since this slightly obfuscates the hash secret
11587 */
11588 if (len == 0) {
11589 _PyUnicode_HASH(self) = 0;
11590 return 0;
11591 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011592 x = _Py_HashBytes(PyUnicode_DATA(self),
11593 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011594 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011595 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596}
11597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011598PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011599 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011601Return the lowest index in S where substring sub is found, \n\
11602such that sub is contained within S[start:end]. Optional\n\
11603arguments start and end are interpreted as in slice notation.\n\
11604\n\
11605Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
11607static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011610 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011611 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011612 PyObject *substring = NULL;
11613 Py_ssize_t start = 0;
11614 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011616 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011619 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011622 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011623
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011624 if (result == -2)
11625 return NULL;
11626
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627 if (result < 0) {
11628 PyErr_SetString(PyExc_ValueError, "substring not found");
11629 return NULL;
11630 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011631
Christian Heimes217cfd12007-12-02 14:31:20 +000011632 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633}
11634
INADA Naoki3ae20562017-01-16 20:41:20 +090011635/*[clinic input]
11636str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637
INADA Naoki3ae20562017-01-16 20:41:20 +090011638Return True if the string is a lowercase string, False otherwise.
11639
11640A string is lowercase if all cased characters in the string are lowercase and
11641there is at least one cased character in the string.
11642[clinic start generated code]*/
11643
11644static PyObject *
11645unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011646/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 Py_ssize_t i, length;
11649 int kind;
11650 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651 int cased;
11652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (PyUnicode_READY(self) == -1)
11654 return NULL;
11655 length = PyUnicode_GET_LENGTH(self);
11656 kind = PyUnicode_KIND(self);
11657 data = PyUnicode_DATA(self);
11658
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011660 if (length == 1)
11661 return PyBool_FromLong(
11662 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011664 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011665 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011666 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011667
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 for (i = 0; i < length; i++) {
11670 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011671
Benjamin Peterson29060642009-01-31 22:14:21 +000011672 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011673 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011674 else if (!cased && Py_UNICODE_ISLOWER(ch))
11675 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011677 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678}
11679
INADA Naoki3ae20562017-01-16 20:41:20 +090011680/*[clinic input]
11681str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682
INADA Naoki3ae20562017-01-16 20:41:20 +090011683Return True if the string is an uppercase string, False otherwise.
11684
11685A string is uppercase if all cased characters in the string are uppercase and
11686there is at least one cased character in the string.
11687[clinic start generated code]*/
11688
11689static PyObject *
11690unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011691/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 Py_ssize_t i, length;
11694 int kind;
11695 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696 int cased;
11697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 if (PyUnicode_READY(self) == -1)
11699 return NULL;
11700 length = PyUnicode_GET_LENGTH(self);
11701 kind = PyUnicode_KIND(self);
11702 data = PyUnicode_DATA(self);
11703
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 if (length == 1)
11706 return PyBool_FromLong(
11707 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011709 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011711 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011712
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 for (i = 0; i < length; i++) {
11715 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011716
Benjamin Peterson29060642009-01-31 22:14:21 +000011717 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011718 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011719 else if (!cased && Py_UNICODE_ISUPPER(ch))
11720 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011722 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723}
11724
INADA Naoki3ae20562017-01-16 20:41:20 +090011725/*[clinic input]
11726str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727
INADA Naoki3ae20562017-01-16 20:41:20 +090011728Return True if the string is a title-cased string, False otherwise.
11729
11730In a title-cased string, upper- and title-case characters may only
11731follow uncased characters and lowercase characters only cased ones.
11732[clinic start generated code]*/
11733
11734static PyObject *
11735unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011736/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011738 Py_ssize_t i, length;
11739 int kind;
11740 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741 int cased, previous_is_cased;
11742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 if (PyUnicode_READY(self) == -1)
11744 return NULL;
11745 length = PyUnicode_GET_LENGTH(self);
11746 kind = PyUnicode_KIND(self);
11747 data = PyUnicode_DATA(self);
11748
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011750 if (length == 1) {
11751 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11752 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11753 (Py_UNICODE_ISUPPER(ch) != 0));
11754 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011756 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011758 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011759
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760 cased = 0;
11761 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 for (i = 0; i < length; i++) {
11763 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011764
Benjamin Peterson29060642009-01-31 22:14:21 +000011765 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11766 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011767 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011768 previous_is_cased = 1;
11769 cased = 1;
11770 }
11771 else if (Py_UNICODE_ISLOWER(ch)) {
11772 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011773 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011774 previous_is_cased = 1;
11775 cased = 1;
11776 }
11777 else
11778 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011780 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781}
11782
INADA Naoki3ae20562017-01-16 20:41:20 +090011783/*[clinic input]
11784str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785
INADA Naoki3ae20562017-01-16 20:41:20 +090011786Return True if the string is a whitespace string, False otherwise.
11787
11788A string is whitespace if all characters in the string are whitespace and there
11789is at least one character in the string.
11790[clinic start generated code]*/
11791
11792static PyObject *
11793unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011794/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011796 Py_ssize_t i, length;
11797 int kind;
11798 void *data;
11799
11800 if (PyUnicode_READY(self) == -1)
11801 return NULL;
11802 length = PyUnicode_GET_LENGTH(self);
11803 kind = PyUnicode_KIND(self);
11804 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011807 if (length == 1)
11808 return PyBool_FromLong(
11809 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011811 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011812 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011813 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 for (i = 0; i < length; i++) {
11816 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011817 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011818 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011820 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821}
11822
INADA Naoki3ae20562017-01-16 20:41:20 +090011823/*[clinic input]
11824str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011825
INADA Naoki3ae20562017-01-16 20:41:20 +090011826Return True if the string is an alphabetic string, False otherwise.
11827
11828A string is alphabetic if all characters in the string are alphabetic and there
11829is at least one character in the string.
11830[clinic start generated code]*/
11831
11832static PyObject *
11833unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011834/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011835{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011836 Py_ssize_t i, length;
11837 int kind;
11838 void *data;
11839
11840 if (PyUnicode_READY(self) == -1)
11841 return NULL;
11842 length = PyUnicode_GET_LENGTH(self);
11843 kind = PyUnicode_KIND(self);
11844 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011845
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011846 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011847 if (length == 1)
11848 return PyBool_FromLong(
11849 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850
11851 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011853 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011854
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011855 for (i = 0; i < length; i++) {
11856 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011857 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011858 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011859 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011860}
11861
INADA Naoki3ae20562017-01-16 20:41:20 +090011862/*[clinic input]
11863str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011864
INADA Naoki3ae20562017-01-16 20:41:20 +090011865Return True if the string is an alpha-numeric string, False otherwise.
11866
11867A string is alpha-numeric if all characters in the string are alpha-numeric and
11868there is at least one character in the string.
11869[clinic start generated code]*/
11870
11871static PyObject *
11872unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011873/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011874{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 int kind;
11876 void *data;
11877 Py_ssize_t len, i;
11878
11879 if (PyUnicode_READY(self) == -1)
11880 return NULL;
11881
11882 kind = PyUnicode_KIND(self);
11883 data = PyUnicode_DATA(self);
11884 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011885
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011886 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011887 if (len == 1) {
11888 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11889 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11890 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011891
11892 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011894 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011895
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 for (i = 0; i < len; i++) {
11897 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011898 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011899 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011900 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011901 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011902}
11903
INADA Naoki3ae20562017-01-16 20:41:20 +090011904/*[clinic input]
11905str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906
INADA Naoki3ae20562017-01-16 20:41:20 +090011907Return True if the string is a decimal string, False otherwise.
11908
11909A string is a decimal string if all characters in the string are decimal and
11910there is at least one character in the string.
11911[clinic start generated code]*/
11912
11913static PyObject *
11914unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011915/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011917 Py_ssize_t i, length;
11918 int kind;
11919 void *data;
11920
11921 if (PyUnicode_READY(self) == -1)
11922 return NULL;
11923 length = PyUnicode_GET_LENGTH(self);
11924 kind = PyUnicode_KIND(self);
11925 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 if (length == 1)
11929 return PyBool_FromLong(
11930 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011932 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011933 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011934 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011936 for (i = 0; i < length; i++) {
11937 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011938 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011940 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941}
11942
INADA Naoki3ae20562017-01-16 20:41:20 +090011943/*[clinic input]
11944str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
INADA Naoki3ae20562017-01-16 20:41:20 +090011946Return True if the string is a digit string, False otherwise.
11947
11948A string is a digit string if all characters in the string are digits and there
11949is at least one character in the string.
11950[clinic start generated code]*/
11951
11952static PyObject *
11953unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011954/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
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 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11969 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11970 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011972 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011974 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 for (i = 0; i < length; i++) {
11977 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
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.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985
INADA Naoki3ae20562017-01-16 20:41:20 +090011986Return True if the string is a numeric string, False otherwise.
11987
11988A string is numeric if all characters in the string are numeric and there is at
11989least one character in the string.
11990[clinic start generated code]*/
11991
11992static PyObject *
11993unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011994/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +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);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012005
Guido van Rossumd57fd912000-03-10 22:53:23 +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_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012010
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012011 /* 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é Lemburg60bc8092000-06-14 09:18:32 +000012014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 for (i = 0; i < length; i++) {
12016 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012017 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012018 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012019 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012020}
12021
Martin v. Löwis47383402007-08-15 07:32:56 +000012022int
12023PyUnicode_IsIdentifier(PyObject *self)
12024{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025 int kind;
12026 void *data;
12027 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012028 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012029
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030 if (PyUnicode_READY(self) == -1) {
12031 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012032 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 }
12034
12035 /* Special case for empty strings */
12036 if (PyUnicode_GET_LENGTH(self) == 0)
12037 return 0;
12038 kind = PyUnicode_KIND(self);
12039 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012040
12041 /* PEP 3131 says that the first character must be in
12042 XID_Start and subsequent characters in XID_Continue,
12043 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012044 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012045 letters, digits, underscore). However, given the current
12046 definition of XID_Start and XID_Continue, it is sufficient
12047 to check just for these, except that _ must be allowed
12048 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012050 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012051 return 0;
12052
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012053 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012055 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012056 return 1;
12057}
12058
INADA Naoki3ae20562017-01-16 20:41:20 +090012059/*[clinic input]
12060str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012061
INADA Naoki3ae20562017-01-16 20:41:20 +090012062Return True if the string is a valid Python identifier, False otherwise.
12063
12064Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12065"class".
12066[clinic start generated code]*/
12067
12068static PyObject *
12069unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012070/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012071{
12072 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12073}
12074
INADA Naoki3ae20562017-01-16 20:41:20 +090012075/*[clinic input]
12076str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012077
INADA Naoki3ae20562017-01-16 20:41:20 +090012078Return True if the string is printable, False otherwise.
12079
12080A string is printable if all of its characters are considered printable in
12081repr() or if it is empty.
12082[clinic start generated code]*/
12083
12084static PyObject *
12085unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012086/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012087{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 Py_ssize_t i, length;
12089 int kind;
12090 void *data;
12091
12092 if (PyUnicode_READY(self) == -1)
12093 return NULL;
12094 length = PyUnicode_GET_LENGTH(self);
12095 kind = PyUnicode_KIND(self);
12096 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012097
12098 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 if (length == 1)
12100 return PyBool_FromLong(
12101 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012102
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012103 for (i = 0; i < length; i++) {
12104 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012105 Py_RETURN_FALSE;
12106 }
12107 }
12108 Py_RETURN_TRUE;
12109}
12110
INADA Naoki3ae20562017-01-16 20:41:20 +090012111/*[clinic input]
12112str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113
INADA Naoki3ae20562017-01-16 20:41:20 +090012114 iterable: object
12115 /
12116
12117Concatenate any number of strings.
12118
Martin Panter91a88662017-01-24 00:30:06 +000012119The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012120The result is returned as a new string.
12121
12122Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12123[clinic start generated code]*/
12124
12125static PyObject *
12126unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012127/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128{
INADA Naoki3ae20562017-01-16 20:41:20 +090012129 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130}
12131
Martin v. Löwis18e16552006-02-15 17:27:45 +000012132static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012133unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 if (PyUnicode_READY(self) == -1)
12136 return -1;
12137 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138}
12139
INADA Naoki3ae20562017-01-16 20:41:20 +090012140/*[clinic input]
12141str.ljust as unicode_ljust
12142
12143 width: Py_ssize_t
12144 fillchar: Py_UCS4 = ' '
12145 /
12146
12147Return a left-justified string of length width.
12148
12149Padding is done using the specified fill character (default is a space).
12150[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012151
12152static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012153unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12154/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012156 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012157 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158
Victor Stinnerc4b49542011-12-11 22:44:26 +010012159 if (PyUnicode_GET_LENGTH(self) >= width)
12160 return unicode_result_unchanged(self);
12161
12162 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163}
12164
INADA Naoki3ae20562017-01-16 20:41:20 +090012165/*[clinic input]
12166str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012167
INADA Naoki3ae20562017-01-16 20:41:20 +090012168Return a copy of the string converted to lowercase.
12169[clinic start generated code]*/
12170
12171static PyObject *
12172unicode_lower_impl(PyObject *self)
12173/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012175 if (PyUnicode_READY(self) == -1)
12176 return NULL;
12177 if (PyUnicode_IS_ASCII(self))
12178 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012179 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180}
12181
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012182#define LEFTSTRIP 0
12183#define RIGHTSTRIP 1
12184#define BOTHSTRIP 2
12185
12186/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012187static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012188
INADA Naoki3ae20562017-01-16 20:41:20 +090012189#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012190
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012191/* externally visible for str.strip(unicode) */
12192PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012193_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012194{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 void *data;
12196 int kind;
12197 Py_ssize_t i, j, len;
12198 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012199 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012201 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12202 return NULL;
12203
12204 kind = PyUnicode_KIND(self);
12205 data = PyUnicode_DATA(self);
12206 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012207 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12209 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012210 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012211
Benjamin Peterson14339b62009-01-31 16:36:08 +000012212 i = 0;
12213 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012214 while (i < len) {
12215 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12216 if (!BLOOM(sepmask, ch))
12217 break;
12218 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12219 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012220 i++;
12221 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012222 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012223
Benjamin Peterson14339b62009-01-31 16:36:08 +000012224 j = len;
12225 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012226 j--;
12227 while (j >= i) {
12228 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12229 if (!BLOOM(sepmask, ch))
12230 break;
12231 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12232 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012233 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012234 }
12235
Benjamin Peterson29060642009-01-31 22:14:21 +000012236 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012237 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012238
Victor Stinner7931d9a2011-11-04 00:22:48 +010012239 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012240}
12241
12242PyObject*
12243PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12244{
12245 unsigned char *data;
12246 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012247 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248
Victor Stinnerde636f32011-10-01 03:55:54 +020012249 if (PyUnicode_READY(self) == -1)
12250 return NULL;
12251
Victor Stinner684d5fd2012-05-03 02:32:34 +020012252 length = PyUnicode_GET_LENGTH(self);
12253 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012254
Victor Stinner684d5fd2012-05-03 02:32:34 +020012255 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012256 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012257
Victor Stinnerde636f32011-10-01 03:55:54 +020012258 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012259 PyErr_SetString(PyExc_IndexError, "string index out of range");
12260 return NULL;
12261 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012262 if (start >= length || end < start)
12263 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012264
Victor Stinner684d5fd2012-05-03 02:32:34 +020012265 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012266 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012267 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012268 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012269 }
12270 else {
12271 kind = PyUnicode_KIND(self);
12272 data = PyUnicode_1BYTE_DATA(self);
12273 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012274 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012275 length);
12276 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012277}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278
12279static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012280do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012282 Py_ssize_t len, i, j;
12283
12284 if (PyUnicode_READY(self) == -1)
12285 return NULL;
12286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012288
Victor Stinnercc7af722013-04-09 22:39:24 +020012289 if (PyUnicode_IS_ASCII(self)) {
12290 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12291
12292 i = 0;
12293 if (striptype != RIGHTSTRIP) {
12294 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012295 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012296 if (!_Py_ascii_whitespace[ch])
12297 break;
12298 i++;
12299 }
12300 }
12301
12302 j = len;
12303 if (striptype != LEFTSTRIP) {
12304 j--;
12305 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012306 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012307 if (!_Py_ascii_whitespace[ch])
12308 break;
12309 j--;
12310 }
12311 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012312 }
12313 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012314 else {
12315 int kind = PyUnicode_KIND(self);
12316 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012317
Victor Stinnercc7af722013-04-09 22:39:24 +020012318 i = 0;
12319 if (striptype != RIGHTSTRIP) {
12320 while (i < len) {
12321 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12322 if (!Py_UNICODE_ISSPACE(ch))
12323 break;
12324 i++;
12325 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012326 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012327
12328 j = len;
12329 if (striptype != LEFTSTRIP) {
12330 j--;
12331 while (j >= i) {
12332 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12333 if (!Py_UNICODE_ISSPACE(ch))
12334 break;
12335 j--;
12336 }
12337 j++;
12338 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012339 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012340
Victor Stinner7931d9a2011-11-04 00:22:48 +010012341 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012342}
12343
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012344
12345static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012346do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012347{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012348 if (sep != NULL && sep != Py_None) {
12349 if (PyUnicode_Check(sep))
12350 return _PyUnicode_XStrip(self, striptype, sep);
12351 else {
12352 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012353 "%s arg must be None or str",
12354 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012355 return NULL;
12356 }
12357 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012358
Benjamin Peterson14339b62009-01-31 16:36:08 +000012359 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012360}
12361
12362
INADA Naoki3ae20562017-01-16 20:41:20 +090012363/*[clinic input]
12364str.strip as unicode_strip
12365
12366 chars: object = None
12367 /
12368
Victor Stinner0c4a8282017-01-17 02:21:47 +010012369Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012370
12371If chars is given and not None, remove characters in chars instead.
12372[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012373
12374static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012375unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012376/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012377{
INADA Naoki3ae20562017-01-16 20:41:20 +090012378 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012379}
12380
12381
INADA Naoki3ae20562017-01-16 20:41:20 +090012382/*[clinic input]
12383str.lstrip as unicode_lstrip
12384
12385 chars: object = NULL
12386 /
12387
12388Return a copy of the string with leading whitespace removed.
12389
12390If chars is given and not None, remove characters in chars instead.
12391[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012392
12393static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012394unicode_lstrip_impl(PyObject *self, PyObject *chars)
12395/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012396{
INADA Naoki3ae20562017-01-16 20:41:20 +090012397 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012398}
12399
12400
INADA Naoki3ae20562017-01-16 20:41:20 +090012401/*[clinic input]
12402str.rstrip as unicode_rstrip
12403
12404 chars: object = NULL
12405 /
12406
12407Return a copy of the string with trailing whitespace removed.
12408
12409If chars is given and not None, remove characters in chars instead.
12410[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012411
12412static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012413unicode_rstrip_impl(PyObject *self, PyObject *chars)
12414/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012415{
INADA Naoki3ae20562017-01-16 20:41:20 +090012416 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012417}
12418
12419
Guido van Rossumd57fd912000-03-10 22:53:23 +000012420static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012421unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012422{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012423 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012425
Serhiy Storchaka05997252013-01-26 12:14:02 +020012426 if (len < 1)
12427 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012428
Victor Stinnerc4b49542011-12-11 22:44:26 +010012429 /* no repeat, return original string */
12430 if (len == 1)
12431 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012432
Benjamin Petersonbac79492012-01-14 13:34:47 -050012433 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 return NULL;
12435
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012436 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012437 PyErr_SetString(PyExc_OverflowError,
12438 "repeated string is too long");
12439 return NULL;
12440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012441 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012442
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012443 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012444 if (!u)
12445 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012446 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 if (PyUnicode_GET_LENGTH(str) == 1) {
12449 const int kind = PyUnicode_KIND(str);
12450 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012451 if (kind == PyUnicode_1BYTE_KIND) {
12452 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012453 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012454 }
12455 else if (kind == PyUnicode_2BYTE_KIND) {
12456 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012457 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012458 ucs2[n] = fill_char;
12459 } else {
12460 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12461 assert(kind == PyUnicode_4BYTE_KIND);
12462 for (n = 0; n < len; ++n)
12463 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012464 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012465 }
12466 else {
12467 /* number of characters copied this far */
12468 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012469 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012470 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012471 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012473 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012474 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012475 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012476 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012478 }
12479
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012480 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012481 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482}
12483
Alexander Belopolsky40018472011-02-26 01:02:56 +000012484PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012485PyUnicode_Replace(PyObject *str,
12486 PyObject *substr,
12487 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012488 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012490 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12491 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012492 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012493 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494}
12495
INADA Naoki3ae20562017-01-16 20:41:20 +090012496/*[clinic input]
12497str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498
INADA Naoki3ae20562017-01-16 20:41:20 +090012499 old: unicode
12500 new: unicode
12501 count: Py_ssize_t = -1
12502 Maximum number of occurrences to replace.
12503 -1 (the default value) means replace all occurrences.
12504 /
12505
12506Return a copy with all occurrences of substring old replaced by new.
12507
12508If the optional argument count is given, only the first count occurrences are
12509replaced.
12510[clinic start generated code]*/
12511
12512static PyObject *
12513unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12514 Py_ssize_t count)
12515/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012517 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012518 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012519 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520}
12521
Alexander Belopolsky40018472011-02-26 01:02:56 +000012522static PyObject *
12523unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012525 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012526 Py_ssize_t isize;
12527 Py_ssize_t osize, squote, dquote, i, o;
12528 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012529 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012530 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012533 return NULL;
12534
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012535 isize = PyUnicode_GET_LENGTH(unicode);
12536 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538 /* Compute length of output, quote characters, and
12539 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012540 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 max = 127;
12542 squote = dquote = 0;
12543 ikind = PyUnicode_KIND(unicode);
12544 for (i = 0; i < isize; i++) {
12545 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012546 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012547 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012548 case '\'': squote++; break;
12549 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012551 incr = 2;
12552 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553 default:
12554 /* Fast-path ASCII */
12555 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012556 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012558 ;
12559 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012562 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012564 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012566 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012568 if (osize > PY_SSIZE_T_MAX - incr) {
12569 PyErr_SetString(PyExc_OverflowError,
12570 "string is too long to generate repr");
12571 return NULL;
12572 }
12573 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 }
12575
12576 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012577 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012579 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012580 if (dquote)
12581 /* Both squote and dquote present. Use squote,
12582 and escape them */
12583 osize += squote;
12584 else
12585 quote = '"';
12586 }
Victor Stinner55c08782013-04-14 18:45:39 +020012587 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588
12589 repr = PyUnicode_New(osize, max);
12590 if (repr == NULL)
12591 return NULL;
12592 okind = PyUnicode_KIND(repr);
12593 odata = PyUnicode_DATA(repr);
12594
12595 PyUnicode_WRITE(okind, odata, 0, quote);
12596 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012597 if (unchanged) {
12598 _PyUnicode_FastCopyCharacters(repr, 1,
12599 unicode, 0,
12600 isize);
12601 }
12602 else {
12603 for (i = 0, o = 1; i < isize; i++) {
12604 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012605
Victor Stinner55c08782013-04-14 18:45:39 +020012606 /* Escape quotes and backslashes */
12607 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012608 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012609 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012610 continue;
12611 }
12612
12613 /* Map special whitespace to '\t', \n', '\r' */
12614 if (ch == '\t') {
12615 PyUnicode_WRITE(okind, odata, o++, '\\');
12616 PyUnicode_WRITE(okind, odata, o++, 't');
12617 }
12618 else if (ch == '\n') {
12619 PyUnicode_WRITE(okind, odata, o++, '\\');
12620 PyUnicode_WRITE(okind, odata, o++, 'n');
12621 }
12622 else if (ch == '\r') {
12623 PyUnicode_WRITE(okind, odata, o++, '\\');
12624 PyUnicode_WRITE(okind, odata, o++, 'r');
12625 }
12626
12627 /* Map non-printable US ASCII to '\xhh' */
12628 else if (ch < ' ' || ch == 0x7F) {
12629 PyUnicode_WRITE(okind, odata, o++, '\\');
12630 PyUnicode_WRITE(okind, odata, o++, 'x');
12631 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12632 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12633 }
12634
12635 /* Copy ASCII characters as-is */
12636 else if (ch < 0x7F) {
12637 PyUnicode_WRITE(okind, odata, o++, ch);
12638 }
12639
12640 /* Non-ASCII characters */
12641 else {
12642 /* Map Unicode whitespace and control characters
12643 (categories Z* and C* except ASCII space)
12644 */
12645 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12646 PyUnicode_WRITE(okind, odata, o++, '\\');
12647 /* Map 8-bit characters to '\xhh' */
12648 if (ch <= 0xff) {
12649 PyUnicode_WRITE(okind, odata, o++, 'x');
12650 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12651 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12652 }
12653 /* Map 16-bit characters to '\uxxxx' */
12654 else if (ch <= 0xffff) {
12655 PyUnicode_WRITE(okind, odata, o++, 'u');
12656 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12657 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12658 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12659 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12660 }
12661 /* Map 21-bit characters to '\U00xxxxxx' */
12662 else {
12663 PyUnicode_WRITE(okind, odata, o++, 'U');
12664 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12665 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12666 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12667 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12668 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12669 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12670 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12671 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12672 }
12673 }
12674 /* Copy characters as-is */
12675 else {
12676 PyUnicode_WRITE(okind, odata, o++, ch);
12677 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012678 }
12679 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012680 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012682 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012683 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684}
12685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012686PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012687 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688\n\
12689Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012690such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691arguments start and end are interpreted as in slice notation.\n\
12692\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012693Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694
12695static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012696unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012697{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012698 /* initialize variables to prevent gcc warning */
12699 PyObject *substring = NULL;
12700 Py_ssize_t start = 0;
12701 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012702 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012704 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012705 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012707 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012708 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012709
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012710 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012712 if (result == -2)
12713 return NULL;
12714
Christian Heimes217cfd12007-12-02 14:31:20 +000012715 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716}
12717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012718PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012719 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012721Return the highest index in S where substring sub is found,\n\
12722such that sub is contained within S[start:end]. Optional\n\
12723arguments start and end are interpreted as in slice notation.\n\
12724\n\
12725Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726
12727static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012728unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012729{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012730 /* initialize variables to prevent gcc warning */
12731 PyObject *substring = NULL;
12732 Py_ssize_t start = 0;
12733 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012734 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012736 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012737 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012738
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012739 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012741
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012742 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012744 if (result == -2)
12745 return NULL;
12746
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747 if (result < 0) {
12748 PyErr_SetString(PyExc_ValueError, "substring not found");
12749 return NULL;
12750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012751
Christian Heimes217cfd12007-12-02 14:31:20 +000012752 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012753}
12754
INADA Naoki3ae20562017-01-16 20:41:20 +090012755/*[clinic input]
12756str.rjust as unicode_rjust
12757
12758 width: Py_ssize_t
12759 fillchar: Py_UCS4 = ' '
12760 /
12761
12762Return a right-justified string of length width.
12763
12764Padding is done using the specified fill character (default is a space).
12765[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766
12767static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012768unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12769/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012771 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772 return NULL;
12773
Victor Stinnerc4b49542011-12-11 22:44:26 +010012774 if (PyUnicode_GET_LENGTH(self) >= width)
12775 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776
Victor Stinnerc4b49542011-12-11 22:44:26 +010012777 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778}
12779
Alexander Belopolsky40018472011-02-26 01:02:56 +000012780PyObject *
12781PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012783 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012784 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012786 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787}
12788
INADA Naoki3ae20562017-01-16 20:41:20 +090012789/*[clinic input]
12790str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791
INADA Naoki3ae20562017-01-16 20:41:20 +090012792 sep: object = None
12793 The delimiter according which to split the string.
12794 None (the default value) means split according to any whitespace,
12795 and discard empty strings from the result.
12796 maxsplit: Py_ssize_t = -1
12797 Maximum number of splits to do.
12798 -1 (the default value) means no limit.
12799
12800Return a list of the words in the string, using sep as the delimiter string.
12801[clinic start generated code]*/
12802
12803static PyObject *
12804unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12805/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806{
INADA Naoki3ae20562017-01-16 20:41:20 +090012807 if (sep == Py_None)
12808 return split(self, NULL, maxsplit);
12809 if (PyUnicode_Check(sep))
12810 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012811
12812 PyErr_Format(PyExc_TypeError,
12813 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012814 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012815 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816}
12817
Thomas Wouters477c8d52006-05-27 19:21:47 +000012818PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012819PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012820{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012821 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012822 int kind1, kind2;
12823 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012824 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012825
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012826 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012827 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012828
Victor Stinner14f8f022011-10-05 20:58:25 +020012829 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012830 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012831 len1 = PyUnicode_GET_LENGTH(str_obj);
12832 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012833 if (kind1 < kind2 || len1 < len2) {
12834 _Py_INCREF_UNICODE_EMPTY();
12835 if (!unicode_empty)
12836 out = NULL;
12837 else {
12838 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12839 Py_DECREF(unicode_empty);
12840 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012841 return out;
12842 }
12843 buf1 = PyUnicode_DATA(str_obj);
12844 buf2 = PyUnicode_DATA(sep_obj);
12845 if (kind2 != kind1) {
12846 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12847 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012848 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012850
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012851 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012852 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012853 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12854 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12855 else
12856 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012857 break;
12858 case PyUnicode_2BYTE_KIND:
12859 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12860 break;
12861 case PyUnicode_4BYTE_KIND:
12862 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12863 break;
12864 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012865 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012866 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012867
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012868 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012869 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012870
12871 return out;
12872}
12873
12874
12875PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012876PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012877{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012878 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012879 int kind1, kind2;
12880 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012882
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012883 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012885
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012886 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012887 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012888 len1 = PyUnicode_GET_LENGTH(str_obj);
12889 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012890 if (kind1 < kind2 || len1 < len2) {
12891 _Py_INCREF_UNICODE_EMPTY();
12892 if (!unicode_empty)
12893 out = NULL;
12894 else {
12895 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12896 Py_DECREF(unicode_empty);
12897 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012898 return out;
12899 }
12900 buf1 = PyUnicode_DATA(str_obj);
12901 buf2 = PyUnicode_DATA(sep_obj);
12902 if (kind2 != kind1) {
12903 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12904 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012905 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012906 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012907
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012908 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012910 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12911 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12912 else
12913 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012914 break;
12915 case PyUnicode_2BYTE_KIND:
12916 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12917 break;
12918 case PyUnicode_4BYTE_KIND:
12919 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12920 break;
12921 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012922 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012924
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012925 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012926 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012927
12928 return out;
12929}
12930
INADA Naoki3ae20562017-01-16 20:41:20 +090012931/*[clinic input]
12932str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012933
INADA Naoki3ae20562017-01-16 20:41:20 +090012934 sep: object
12935 /
12936
12937Partition the string into three parts using the given separator.
12938
12939This will search for the separator in the string. If the separator is found,
12940returns a 3-tuple containing the part before the separator, the separator
12941itself, and the part after it.
12942
12943If the separator is not found, returns a 3-tuple containing the original string
12944and two empty strings.
12945[clinic start generated code]*/
12946
12947static PyObject *
12948unicode_partition(PyObject *self, PyObject *sep)
12949/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012950{
INADA Naoki3ae20562017-01-16 20:41:20 +090012951 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012952}
12953
INADA Naoki3ae20562017-01-16 20:41:20 +090012954/*[clinic input]
12955str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012956
INADA Naoki3ae20562017-01-16 20:41:20 +090012957Partition the string into three parts using the given separator.
12958
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012959This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012960the separator is found, returns a 3-tuple containing the part before the
12961separator, the separator itself, and the part after it.
12962
12963If the separator is not found, returns a 3-tuple containing two empty strings
12964and the original string.
12965[clinic start generated code]*/
12966
12967static PyObject *
12968unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012969/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012970{
INADA Naoki3ae20562017-01-16 20:41:20 +090012971 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012972}
12973
Alexander Belopolsky40018472011-02-26 01:02:56 +000012974PyObject *
12975PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012976{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012977 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012978 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012979
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012980 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012981}
12982
INADA Naoki3ae20562017-01-16 20:41:20 +090012983/*[clinic input]
12984str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012985
INADA Naoki3ae20562017-01-16 20:41:20 +090012986Return a list of the words in the string, using sep as the delimiter string.
12987
12988Splits are done starting at the end of the string and working to the front.
12989[clinic start generated code]*/
12990
12991static PyObject *
12992unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12993/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012994{
INADA Naoki3ae20562017-01-16 20:41:20 +090012995 if (sep == Py_None)
12996 return rsplit(self, NULL, maxsplit);
12997 if (PyUnicode_Check(sep))
12998 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012999
13000 PyErr_Format(PyExc_TypeError,
13001 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013002 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013003 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013004}
13005
INADA Naoki3ae20562017-01-16 20:41:20 +090013006/*[clinic input]
13007str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013008
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013009 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013010
13011Return a list of the lines in the string, breaking at line boundaries.
13012
13013Line breaks are not included in the resulting list unless keepends is given and
13014true.
13015[clinic start generated code]*/
13016
13017static PyObject *
13018unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013019/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013020{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013021 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013022}
13023
13024static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013025PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013026{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013027 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013028}
13029
INADA Naoki3ae20562017-01-16 20:41:20 +090013030/*[clinic input]
13031str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013032
INADA Naoki3ae20562017-01-16 20:41:20 +090013033Convert uppercase characters to lowercase and lowercase characters to uppercase.
13034[clinic start generated code]*/
13035
13036static PyObject *
13037unicode_swapcase_impl(PyObject *self)
13038/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013039{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013040 if (PyUnicode_READY(self) == -1)
13041 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013042 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013043}
13044
Larry Hastings61272b72014-01-07 12:41:53 -080013045/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013046
Larry Hastings31826802013-10-19 00:09:25 -070013047@staticmethod
13048str.maketrans as unicode_maketrans
13049
13050 x: object
13051
13052 y: unicode=NULL
13053
13054 z: unicode=NULL
13055
13056 /
13057
13058Return a translation table usable for str.translate().
13059
13060If there is only one argument, it must be a dictionary mapping Unicode
13061ordinals (integers) or characters to Unicode ordinals, strings or None.
13062Character keys will be then converted to ordinals.
13063If there are two arguments, they must be strings of equal length, and
13064in the resulting dictionary, each character in x will be mapped to the
13065character at the same position in y. If there is a third argument, it
13066must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013067[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013068
Larry Hastings31826802013-10-19 00:09:25 -070013069static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013070unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013071/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013072{
Georg Brandlceee0772007-11-27 23:48:05 +000013073 PyObject *new = NULL, *key, *value;
13074 Py_ssize_t i = 0;
13075 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013076
Georg Brandlceee0772007-11-27 23:48:05 +000013077 new = PyDict_New();
13078 if (!new)
13079 return NULL;
13080 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013081 int x_kind, y_kind, z_kind;
13082 void *x_data, *y_data, *z_data;
13083
Georg Brandlceee0772007-11-27 23:48:05 +000013084 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013085 if (!PyUnicode_Check(x)) {
13086 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13087 "be a string if there is a second argument");
13088 goto err;
13089 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013090 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013091 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13092 "arguments must have equal length");
13093 goto err;
13094 }
13095 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013096 x_kind = PyUnicode_KIND(x);
13097 y_kind = PyUnicode_KIND(y);
13098 x_data = PyUnicode_DATA(x);
13099 y_data = PyUnicode_DATA(y);
13100 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13101 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013102 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013103 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013104 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013105 if (!value) {
13106 Py_DECREF(key);
13107 goto err;
13108 }
Georg Brandlceee0772007-11-27 23:48:05 +000013109 res = PyDict_SetItem(new, key, value);
13110 Py_DECREF(key);
13111 Py_DECREF(value);
13112 if (res < 0)
13113 goto err;
13114 }
13115 /* create entries for deleting chars in z */
13116 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013117 z_kind = PyUnicode_KIND(z);
13118 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013119 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013120 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013121 if (!key)
13122 goto err;
13123 res = PyDict_SetItem(new, key, Py_None);
13124 Py_DECREF(key);
13125 if (res < 0)
13126 goto err;
13127 }
13128 }
13129 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013130 int kind;
13131 void *data;
13132
Georg Brandlceee0772007-11-27 23:48:05 +000013133 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013134 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013135 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13136 "to maketrans it must be a dict");
13137 goto err;
13138 }
13139 /* copy entries into the new dict, converting string keys to int keys */
13140 while (PyDict_Next(x, &i, &key, &value)) {
13141 if (PyUnicode_Check(key)) {
13142 /* convert string keys to integer keys */
13143 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013144 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013145 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13146 "table must be of length 1");
13147 goto err;
13148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013149 kind = PyUnicode_KIND(key);
13150 data = PyUnicode_DATA(key);
13151 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013152 if (!newkey)
13153 goto err;
13154 res = PyDict_SetItem(new, newkey, value);
13155 Py_DECREF(newkey);
13156 if (res < 0)
13157 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013158 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013159 /* just keep integer keys */
13160 if (PyDict_SetItem(new, key, value) < 0)
13161 goto err;
13162 } else {
13163 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13164 "be strings or integers");
13165 goto err;
13166 }
13167 }
13168 }
13169 return new;
13170 err:
13171 Py_DECREF(new);
13172 return NULL;
13173}
13174
INADA Naoki3ae20562017-01-16 20:41:20 +090013175/*[clinic input]
13176str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177
INADA Naoki3ae20562017-01-16 20:41:20 +090013178 table: object
13179 Translation table, which must be a mapping of Unicode ordinals to
13180 Unicode ordinals, strings, or None.
13181 /
13182
13183Replace each character in the string using the given translation table.
13184
13185The table must implement lookup/indexing via __getitem__, for instance a
13186dictionary or list. If this operation raises LookupError, the character is
13187left untouched. Characters mapped to None are deleted.
13188[clinic start generated code]*/
13189
13190static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013191unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013192/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013194 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195}
13196
INADA Naoki3ae20562017-01-16 20:41:20 +090013197/*[clinic input]
13198str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199
INADA Naoki3ae20562017-01-16 20:41:20 +090013200Return a copy of the string converted to uppercase.
13201[clinic start generated code]*/
13202
13203static PyObject *
13204unicode_upper_impl(PyObject *self)
13205/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013206{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013207 if (PyUnicode_READY(self) == -1)
13208 return NULL;
13209 if (PyUnicode_IS_ASCII(self))
13210 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013211 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212}
13213
INADA Naoki3ae20562017-01-16 20:41:20 +090013214/*[clinic input]
13215str.zfill as unicode_zfill
13216
13217 width: Py_ssize_t
13218 /
13219
13220Pad a numeric string with zeros on the left, to fill a field of the given width.
13221
13222The string is never truncated.
13223[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224
13225static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013226unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013227/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013228{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013229 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013230 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013231 int kind;
13232 void *data;
13233 Py_UCS4 chr;
13234
Benjamin Petersonbac79492012-01-14 13:34:47 -050013235 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013236 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237
Victor Stinnerc4b49542011-12-11 22:44:26 +010013238 if (PyUnicode_GET_LENGTH(self) >= width)
13239 return unicode_result_unchanged(self);
13240
13241 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242
13243 u = pad(self, fill, 0, '0');
13244
Walter Dörwald068325e2002-04-15 13:36:47 +000013245 if (u == NULL)
13246 return NULL;
13247
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013248 kind = PyUnicode_KIND(u);
13249 data = PyUnicode_DATA(u);
13250 chr = PyUnicode_READ(kind, data, fill);
13251
13252 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013253 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013254 PyUnicode_WRITE(kind, data, 0, chr);
13255 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256 }
13257
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013258 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013259 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013260}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013261
13262#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013263static PyObject *
13264unicode__decimal2ascii(PyObject *self)
13265{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013266 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013267}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013268#endif
13269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013270PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013271 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013273Return True if S starts with the specified prefix, False otherwise.\n\
13274With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013275With optional end, stop comparing S at that position.\n\
13276prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013277
13278static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013279unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013280 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013282 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013283 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013284 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013285 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013286 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013287
Jesus Ceaac451502011-04-20 17:09:23 +020013288 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013290 if (PyTuple_Check(subobj)) {
13291 Py_ssize_t i;
13292 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013293 substring = PyTuple_GET_ITEM(subobj, i);
13294 if (!PyUnicode_Check(substring)) {
13295 PyErr_Format(PyExc_TypeError,
13296 "tuple for startswith must only contain str, "
13297 "not %.100s",
13298 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013299 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013300 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013301 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013302 if (result == -1)
13303 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013304 if (result) {
13305 Py_RETURN_TRUE;
13306 }
13307 }
13308 /* nothing matched */
13309 Py_RETURN_FALSE;
13310 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013311 if (!PyUnicode_Check(subobj)) {
13312 PyErr_Format(PyExc_TypeError,
13313 "startswith first arg must be str or "
13314 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013315 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013316 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013317 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013318 if (result == -1)
13319 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013320 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013321}
13322
13323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013324PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013325 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013327Return True if S ends with the specified suffix, False otherwise.\n\
13328With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013329With optional end, stop comparing S at that position.\n\
13330suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013331
13332static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013333unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013334 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013335{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013336 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013337 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013338 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013339 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013340 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013341
Jesus Ceaac451502011-04-20 17:09:23 +020013342 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013343 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013344 if (PyTuple_Check(subobj)) {
13345 Py_ssize_t i;
13346 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013347 substring = PyTuple_GET_ITEM(subobj, i);
13348 if (!PyUnicode_Check(substring)) {
13349 PyErr_Format(PyExc_TypeError,
13350 "tuple for endswith must only contain str, "
13351 "not %.100s",
13352 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013354 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013355 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013356 if (result == -1)
13357 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013358 if (result) {
13359 Py_RETURN_TRUE;
13360 }
13361 }
13362 Py_RETURN_FALSE;
13363 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013364 if (!PyUnicode_Check(subobj)) {
13365 PyErr_Format(PyExc_TypeError,
13366 "endswith first arg must be str or "
13367 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013368 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013369 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013370 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013371 if (result == -1)
13372 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013373 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013374}
13375
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013376static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013377_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013378{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013379 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13380 writer->data = PyUnicode_DATA(writer->buffer);
13381
13382 if (!writer->readonly) {
13383 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013384 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013385 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013386 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013387 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13388 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13389 writer->kind = PyUnicode_WCHAR_KIND;
13390 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13391
Victor Stinner8f674cc2013-04-17 23:02:17 +020013392 /* Copy-on-write mode: set buffer size to 0 so
13393 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13394 * next write. */
13395 writer->size = 0;
13396 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013397}
13398
Victor Stinnerd3f08822012-05-29 12:57:52 +020013399void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013400_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013401{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013402 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013403
13404 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013405 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013406
13407 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13408 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13409 writer->kind = PyUnicode_WCHAR_KIND;
13410 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013411}
13412
Victor Stinnerd3f08822012-05-29 12:57:52 +020013413int
13414_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13415 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013416{
13417 Py_ssize_t newlen;
13418 PyObject *newbuffer;
13419
Victor Stinner2740e462016-09-06 16:58:36 -070013420 assert(maxchar <= MAX_UNICODE);
13421
Victor Stinnerca9381e2015-09-22 00:58:32 +020013422 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013423 assert((maxchar > writer->maxchar && length >= 0)
13424 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013425
Victor Stinner202fdca2012-05-07 12:47:02 +020013426 if (length > PY_SSIZE_T_MAX - writer->pos) {
13427 PyErr_NoMemory();
13428 return -1;
13429 }
13430 newlen = writer->pos + length;
13431
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013432 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013433
Victor Stinnerd3f08822012-05-29 12:57:52 +020013434 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013435 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013436 if (writer->overallocate
13437 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13438 /* overallocate to limit the number of realloc() */
13439 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013440 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013441 if (newlen < writer->min_length)
13442 newlen = writer->min_length;
13443
Victor Stinnerd3f08822012-05-29 12:57:52 +020013444 writer->buffer = PyUnicode_New(newlen, maxchar);
13445 if (writer->buffer == NULL)
13446 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013447 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013448 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013449 if (writer->overallocate
13450 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13451 /* overallocate to limit the number of realloc() */
13452 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013453 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013454 if (newlen < writer->min_length)
13455 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013456
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013457 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013458 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013459 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013460 newbuffer = PyUnicode_New(newlen, maxchar);
13461 if (newbuffer == NULL)
13462 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013463 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13464 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013465 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013466 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013467 }
13468 else {
13469 newbuffer = resize_compact(writer->buffer, newlen);
13470 if (newbuffer == NULL)
13471 return -1;
13472 }
13473 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013474 }
13475 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013476 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013477 newbuffer = PyUnicode_New(writer->size, maxchar);
13478 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013479 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013480 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13481 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013482 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013483 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013484 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013485 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013486
13487#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013488}
13489
Victor Stinnerca9381e2015-09-22 00:58:32 +020013490int
13491_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13492 enum PyUnicode_Kind kind)
13493{
13494 Py_UCS4 maxchar;
13495
13496 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13497 assert(writer->kind < kind);
13498
13499 switch (kind)
13500 {
13501 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13502 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13503 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13504 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013505 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013506 }
13507
13508 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13509}
13510
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013511static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013512_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013513{
Victor Stinner2740e462016-09-06 16:58:36 -070013514 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013515 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13516 return -1;
13517 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13518 writer->pos++;
13519 return 0;
13520}
13521
13522int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013523_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13524{
13525 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13526}
13527
13528int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013529_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13530{
13531 Py_UCS4 maxchar;
13532 Py_ssize_t len;
13533
13534 if (PyUnicode_READY(str) == -1)
13535 return -1;
13536 len = PyUnicode_GET_LENGTH(str);
13537 if (len == 0)
13538 return 0;
13539 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13540 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013541 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013542 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013543 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544 Py_INCREF(str);
13545 writer->buffer = str;
13546 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013547 writer->pos += len;
13548 return 0;
13549 }
13550 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13551 return -1;
13552 }
13553 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13554 str, 0, len);
13555 writer->pos += len;
13556 return 0;
13557}
13558
Victor Stinnere215d962012-10-06 23:03:36 +020013559int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013560_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13561 Py_ssize_t start, Py_ssize_t end)
13562{
13563 Py_UCS4 maxchar;
13564 Py_ssize_t len;
13565
13566 if (PyUnicode_READY(str) == -1)
13567 return -1;
13568
13569 assert(0 <= start);
13570 assert(end <= PyUnicode_GET_LENGTH(str));
13571 assert(start <= end);
13572
13573 if (end == 0)
13574 return 0;
13575
13576 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13577 return _PyUnicodeWriter_WriteStr(writer, str);
13578
13579 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13580 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13581 else
13582 maxchar = writer->maxchar;
13583 len = end - start;
13584
13585 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13586 return -1;
13587
13588 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13589 str, start, len);
13590 writer->pos += len;
13591 return 0;
13592}
13593
13594int
Victor Stinner4a587072013-11-19 12:54:53 +010013595_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13596 const char *ascii, Py_ssize_t len)
13597{
13598 if (len == -1)
13599 len = strlen(ascii);
13600
13601 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13602
13603 if (writer->buffer == NULL && !writer->overallocate) {
13604 PyObject *str;
13605
13606 str = _PyUnicode_FromASCII(ascii, len);
13607 if (str == NULL)
13608 return -1;
13609
13610 writer->readonly = 1;
13611 writer->buffer = str;
13612 _PyUnicodeWriter_Update(writer);
13613 writer->pos += len;
13614 return 0;
13615 }
13616
13617 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13618 return -1;
13619
13620 switch (writer->kind)
13621 {
13622 case PyUnicode_1BYTE_KIND:
13623 {
13624 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13625 Py_UCS1 *data = writer->data;
13626
Christian Heimesf051e432016-09-13 20:22:02 +020013627 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013628 break;
13629 }
13630 case PyUnicode_2BYTE_KIND:
13631 {
13632 _PyUnicode_CONVERT_BYTES(
13633 Py_UCS1, Py_UCS2,
13634 ascii, ascii + len,
13635 (Py_UCS2 *)writer->data + writer->pos);
13636 break;
13637 }
13638 case PyUnicode_4BYTE_KIND:
13639 {
13640 _PyUnicode_CONVERT_BYTES(
13641 Py_UCS1, Py_UCS4,
13642 ascii, ascii + len,
13643 (Py_UCS4 *)writer->data + writer->pos);
13644 break;
13645 }
13646 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013647 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013648 }
13649
13650 writer->pos += len;
13651 return 0;
13652}
13653
13654int
13655_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13656 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013657{
13658 Py_UCS4 maxchar;
13659
13660 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13661 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13662 return -1;
13663 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13664 writer->pos += len;
13665 return 0;
13666}
13667
Victor Stinnerd3f08822012-05-29 12:57:52 +020013668PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013669_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013670{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013671 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013672
Victor Stinnerd3f08822012-05-29 12:57:52 +020013673 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013674 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013675 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013676 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013677
13678 str = writer->buffer;
13679 writer->buffer = NULL;
13680
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013681 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013682 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13683 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013684 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013685
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013686 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13687 PyObject *str2;
13688 str2 = resize_compact(str, writer->pos);
13689 if (str2 == NULL) {
13690 Py_DECREF(str);
13691 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013692 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013693 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013694 }
13695
Victor Stinner15a0bd32013-07-08 22:29:55 +020013696 assert(_PyUnicode_CheckConsistency(str, 1));
13697 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013698}
13699
Victor Stinnerd3f08822012-05-29 12:57:52 +020013700void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013701_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013702{
13703 Py_CLEAR(writer->buffer);
13704}
13705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013706#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013707
13708PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013709 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013710\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013711Return a formatted version of S, using substitutions from args and kwargs.\n\
13712The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013713
Eric Smith27bbca62010-11-04 17:06:58 +000013714PyDoc_STRVAR(format_map__doc__,
13715 "S.format_map(mapping) -> str\n\
13716\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013717Return a formatted version of S, using substitutions from mapping.\n\
13718The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013719
INADA Naoki3ae20562017-01-16 20:41:20 +090013720/*[clinic input]
13721str.__format__ as unicode___format__
13722
13723 format_spec: unicode
13724 /
13725
13726Return a formatted version of the string as described by format_spec.
13727[clinic start generated code]*/
13728
Eric Smith4a7d76d2008-05-30 18:10:19 +000013729static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013730unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013731/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013732{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013733 _PyUnicodeWriter writer;
13734 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013735
Victor Stinnerd3f08822012-05-29 12:57:52 +020013736 if (PyUnicode_READY(self) == -1)
13737 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013738 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013739 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13740 self, format_spec, 0,
13741 PyUnicode_GET_LENGTH(format_spec));
13742 if (ret == -1) {
13743 _PyUnicodeWriter_Dealloc(&writer);
13744 return NULL;
13745 }
13746 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013747}
13748
INADA Naoki3ae20562017-01-16 20:41:20 +090013749/*[clinic input]
13750str.__sizeof__ as unicode_sizeof
13751
13752Return the size of the string in memory, in bytes.
13753[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013754
13755static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013756unicode_sizeof_impl(PyObject *self)
13757/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013758{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013759 Py_ssize_t size;
13760
13761 /* If it's a compact object, account for base structure +
13762 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013763 if (PyUnicode_IS_COMPACT_ASCII(self))
13764 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13765 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013766 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013767 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013768 else {
13769 /* If it is a two-block object, account for base object, and
13770 for character block if present. */
13771 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013772 if (_PyUnicode_DATA_ANY(self))
13773 size += (PyUnicode_GET_LENGTH(self) + 1) *
13774 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013775 }
13776 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013777 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013778 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13779 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13780 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13781 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013782
13783 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013784}
13785
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013786static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013787unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013788{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013789 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013790 if (!copy)
13791 return NULL;
13792 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013793}
13794
Guido van Rossumd57fd912000-03-10 22:53:23 +000013795static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013796 UNICODE_ENCODE_METHODDEF
13797 UNICODE_REPLACE_METHODDEF
13798 UNICODE_SPLIT_METHODDEF
13799 UNICODE_RSPLIT_METHODDEF
13800 UNICODE_JOIN_METHODDEF
13801 UNICODE_CAPITALIZE_METHODDEF
13802 UNICODE_CASEFOLD_METHODDEF
13803 UNICODE_TITLE_METHODDEF
13804 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013805 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013806 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013807 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013808 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013809 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013810 UNICODE_LJUST_METHODDEF
13811 UNICODE_LOWER_METHODDEF
13812 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013813 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13814 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013815 UNICODE_RJUST_METHODDEF
13816 UNICODE_RSTRIP_METHODDEF
13817 UNICODE_RPARTITION_METHODDEF
13818 UNICODE_SPLITLINES_METHODDEF
13819 UNICODE_STRIP_METHODDEF
13820 UNICODE_SWAPCASE_METHODDEF
13821 UNICODE_TRANSLATE_METHODDEF
13822 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013823 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13824 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013825 UNICODE_ISLOWER_METHODDEF
13826 UNICODE_ISUPPER_METHODDEF
13827 UNICODE_ISTITLE_METHODDEF
13828 UNICODE_ISSPACE_METHODDEF
13829 UNICODE_ISDECIMAL_METHODDEF
13830 UNICODE_ISDIGIT_METHODDEF
13831 UNICODE_ISNUMERIC_METHODDEF
13832 UNICODE_ISALPHA_METHODDEF
13833 UNICODE_ISALNUM_METHODDEF
13834 UNICODE_ISIDENTIFIER_METHODDEF
13835 UNICODE_ISPRINTABLE_METHODDEF
13836 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013837 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013838 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013839 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013840 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013841 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013842#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013843 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013844 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013845#endif
13846
Benjamin Peterson14339b62009-01-31 16:36:08 +000013847 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013848 {NULL, NULL}
13849};
13850
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013851static PyObject *
13852unicode_mod(PyObject *v, PyObject *w)
13853{
Brian Curtindfc80e32011-08-10 20:28:54 -050013854 if (!PyUnicode_Check(v))
13855 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013856 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013857}
13858
13859static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013860 0, /*nb_add*/
13861 0, /*nb_subtract*/
13862 0, /*nb_multiply*/
13863 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013864};
13865
Guido van Rossumd57fd912000-03-10 22:53:23 +000013866static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013867 (lenfunc) unicode_length, /* sq_length */
13868 PyUnicode_Concat, /* sq_concat */
13869 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13870 (ssizeargfunc) unicode_getitem, /* sq_item */
13871 0, /* sq_slice */
13872 0, /* sq_ass_item */
13873 0, /* sq_ass_slice */
13874 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013875};
13876
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013877static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013878unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013879{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013880 if (PyUnicode_READY(self) == -1)
13881 return NULL;
13882
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013883 if (PyIndex_Check(item)) {
13884 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013885 if (i == -1 && PyErr_Occurred())
13886 return NULL;
13887 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013888 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013889 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013890 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013891 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013892 PyObject *result;
13893 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013894 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013895 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013896
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013897 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013898 return NULL;
13899 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013900 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13901 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013902
13903 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013904 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013905 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013906 slicelength == PyUnicode_GET_LENGTH(self)) {
13907 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013908 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013909 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013910 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013911 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013912 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013913 src_kind = PyUnicode_KIND(self);
13914 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013915 if (!PyUnicode_IS_ASCII(self)) {
13916 kind_limit = kind_maxchar_limit(src_kind);
13917 max_char = 0;
13918 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13919 ch = PyUnicode_READ(src_kind, src_data, cur);
13920 if (ch > max_char) {
13921 max_char = ch;
13922 if (max_char >= kind_limit)
13923 break;
13924 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013925 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013926 }
Victor Stinner55c99112011-10-13 01:17:06 +020013927 else
13928 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013929 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013930 if (result == NULL)
13931 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013932 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013933 dest_data = PyUnicode_DATA(result);
13934
13935 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013936 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13937 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013938 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013939 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013940 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013941 } else {
13942 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13943 return NULL;
13944 }
13945}
13946
13947static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013948 (lenfunc)unicode_length, /* mp_length */
13949 (binaryfunc)unicode_subscript, /* mp_subscript */
13950 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013951};
13952
Guido van Rossumd57fd912000-03-10 22:53:23 +000013953
Guido van Rossumd57fd912000-03-10 22:53:23 +000013954/* Helpers for PyUnicode_Format() */
13955
Victor Stinnera47082312012-10-04 02:19:54 +020013956struct unicode_formatter_t {
13957 PyObject *args;
13958 int args_owned;
13959 Py_ssize_t arglen, argidx;
13960 PyObject *dict;
13961
13962 enum PyUnicode_Kind fmtkind;
13963 Py_ssize_t fmtcnt, fmtpos;
13964 void *fmtdata;
13965 PyObject *fmtstr;
13966
13967 _PyUnicodeWriter writer;
13968};
13969
13970struct unicode_format_arg_t {
13971 Py_UCS4 ch;
13972 int flags;
13973 Py_ssize_t width;
13974 int prec;
13975 int sign;
13976};
13977
Guido van Rossumd57fd912000-03-10 22:53:23 +000013978static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013979unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013980{
Victor Stinnera47082312012-10-04 02:19:54 +020013981 Py_ssize_t argidx = ctx->argidx;
13982
13983 if (argidx < ctx->arglen) {
13984 ctx->argidx++;
13985 if (ctx->arglen < 0)
13986 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013987 else
Victor Stinnera47082312012-10-04 02:19:54 +020013988 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013989 }
13990 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013991 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013992 return NULL;
13993}
13994
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013995/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013996
Victor Stinnera47082312012-10-04 02:19:54 +020013997/* Format a float into the writer if the writer is not NULL, or into *p_output
13998 otherwise.
13999
14000 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014001static int
Victor Stinnera47082312012-10-04 02:19:54 +020014002formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14003 PyObject **p_output,
14004 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014005{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014006 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014007 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014008 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014009 int prec;
14010 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014011
Guido van Rossumd57fd912000-03-10 22:53:23 +000014012 x = PyFloat_AsDouble(v);
14013 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014014 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014015
Victor Stinnera47082312012-10-04 02:19:54 +020014016 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014017 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014018 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014019
Victor Stinnera47082312012-10-04 02:19:54 +020014020 if (arg->flags & F_ALT)
14021 dtoa_flags = Py_DTSF_ALT;
14022 else
14023 dtoa_flags = 0;
14024 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014025 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014026 return -1;
14027 len = strlen(p);
14028 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014029 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014030 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014031 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014032 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014033 }
14034 else
14035 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014036 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014037 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014038}
14039
Victor Stinnerd0880d52012-04-27 23:40:13 +020014040/* formatlong() emulates the format codes d, u, o, x and X, and
14041 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14042 * Python's regular ints.
14043 * Return value: a new PyUnicodeObject*, or NULL if error.
14044 * The output string is of the form
14045 * "-"? ("0x" | "0X")? digit+
14046 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14047 * set in flags. The case of hex digits will be correct,
14048 * There will be at least prec digits, zero-filled on the left if
14049 * necessary to get that many.
14050 * val object to be converted
14051 * flags bitmask of format flags; only F_ALT is looked at
14052 * prec minimum number of digits; 0-fill on left if needed
14053 * type a character in [duoxX]; u acts the same as d
14054 *
14055 * CAUTION: o, x and X conversions on regular ints can never
14056 * produce a '-' sign, but can for Python's unbounded ints.
14057 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014058PyObject *
14059_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014060{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014061 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014062 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014063 Py_ssize_t i;
14064 int sign; /* 1 if '-', else 0 */
14065 int len; /* number of characters */
14066 Py_ssize_t llen;
14067 int numdigits; /* len == numnondigits + numdigits */
14068 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014069
Victor Stinnerd0880d52012-04-27 23:40:13 +020014070 /* Avoid exceeding SSIZE_T_MAX */
14071 if (prec > INT_MAX-3) {
14072 PyErr_SetString(PyExc_OverflowError,
14073 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014074 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014075 }
14076
14077 assert(PyLong_Check(val));
14078
14079 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014080 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014081 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014082 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014083 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014084 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014085 /* int and int subclasses should print numerically when a numeric */
14086 /* format code is used (see issue18780) */
14087 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014088 break;
14089 case 'o':
14090 numnondigits = 2;
14091 result = PyNumber_ToBase(val, 8);
14092 break;
14093 case 'x':
14094 case 'X':
14095 numnondigits = 2;
14096 result = PyNumber_ToBase(val, 16);
14097 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014098 }
14099 if (!result)
14100 return NULL;
14101
14102 assert(unicode_modifiable(result));
14103 assert(PyUnicode_IS_READY(result));
14104 assert(PyUnicode_IS_ASCII(result));
14105
14106 /* To modify the string in-place, there can only be one reference. */
14107 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014108 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014109 PyErr_BadInternalCall();
14110 return NULL;
14111 }
14112 buf = PyUnicode_DATA(result);
14113 llen = PyUnicode_GET_LENGTH(result);
14114 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014115 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014116 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014117 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014118 return NULL;
14119 }
14120 len = (int)llen;
14121 sign = buf[0] == '-';
14122 numnondigits += sign;
14123 numdigits = len - numnondigits;
14124 assert(numdigits > 0);
14125
14126 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014127 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014128 (type == 'o' || type == 'x' || type == 'X'))) {
14129 assert(buf[sign] == '0');
14130 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14131 buf[sign+1] == 'o');
14132 numnondigits -= 2;
14133 buf += 2;
14134 len -= 2;
14135 if (sign)
14136 buf[0] = '-';
14137 assert(len == numnondigits + numdigits);
14138 assert(numdigits > 0);
14139 }
14140
14141 /* Fill with leading zeroes to meet minimum width. */
14142 if (prec > numdigits) {
14143 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14144 numnondigits + prec);
14145 char *b1;
14146 if (!r1) {
14147 Py_DECREF(result);
14148 return NULL;
14149 }
14150 b1 = PyBytes_AS_STRING(r1);
14151 for (i = 0; i < numnondigits; ++i)
14152 *b1++ = *buf++;
14153 for (i = 0; i < prec - numdigits; i++)
14154 *b1++ = '0';
14155 for (i = 0; i < numdigits; i++)
14156 *b1++ = *buf++;
14157 *b1 = '\0';
14158 Py_DECREF(result);
14159 result = r1;
14160 buf = PyBytes_AS_STRING(result);
14161 len = numnondigits + prec;
14162 }
14163
14164 /* Fix up case for hex conversions. */
14165 if (type == 'X') {
14166 /* Need to convert all lower case letters to upper case.
14167 and need to convert 0x to 0X (and -0x to -0X). */
14168 for (i = 0; i < len; i++)
14169 if (buf[i] >= 'a' && buf[i] <= 'x')
14170 buf[i] -= 'a'-'A';
14171 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014172 if (!PyUnicode_Check(result)
14173 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014174 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014175 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014176 Py_DECREF(result);
14177 result = unicode;
14178 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014179 else if (len != PyUnicode_GET_LENGTH(result)) {
14180 if (PyUnicode_Resize(&result, len) < 0)
14181 Py_CLEAR(result);
14182 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014183 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014184}
14185
Ethan Furmandf3ed242014-01-05 06:50:30 -080014186/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014187 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014188 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014189 * -1 and raise an exception on error */
14190static int
Victor Stinnera47082312012-10-04 02:19:54 +020014191mainformatlong(PyObject *v,
14192 struct unicode_format_arg_t *arg,
14193 PyObject **p_output,
14194 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014195{
14196 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014197 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014198
14199 if (!PyNumber_Check(v))
14200 goto wrongtype;
14201
Ethan Furman9ab74802014-03-21 06:38:46 -070014202 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014203 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014204 if (type == 'o' || type == 'x' || type == 'X') {
14205 iobj = PyNumber_Index(v);
14206 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014207 if (PyErr_ExceptionMatches(PyExc_TypeError))
14208 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014209 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014210 }
14211 }
14212 else {
14213 iobj = PyNumber_Long(v);
14214 if (iobj == NULL ) {
14215 if (PyErr_ExceptionMatches(PyExc_TypeError))
14216 goto wrongtype;
14217 return -1;
14218 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014219 }
14220 assert(PyLong_Check(iobj));
14221 }
14222 else {
14223 iobj = v;
14224 Py_INCREF(iobj);
14225 }
14226
14227 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014228 && arg->width == -1 && arg->prec == -1
14229 && !(arg->flags & (F_SIGN | F_BLANK))
14230 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014231 {
14232 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014233 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014234 int base;
14235
Victor Stinnera47082312012-10-04 02:19:54 +020014236 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014237 {
14238 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014239 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014240 case 'd':
14241 case 'i':
14242 case 'u':
14243 base = 10;
14244 break;
14245 case 'o':
14246 base = 8;
14247 break;
14248 case 'x':
14249 case 'X':
14250 base = 16;
14251 break;
14252 }
14253
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014254 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14255 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014256 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014257 }
14258 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014259 return 1;
14260 }
14261
Ethan Furmanb95b5612015-01-23 20:05:18 -080014262 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014263 Py_DECREF(iobj);
14264 if (res == NULL)
14265 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014266 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014267 return 0;
14268
14269wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014270 switch(type)
14271 {
14272 case 'o':
14273 case 'x':
14274 case 'X':
14275 PyErr_Format(PyExc_TypeError,
14276 "%%%c format: an integer is required, "
14277 "not %.200s",
14278 type, Py_TYPE(v)->tp_name);
14279 break;
14280 default:
14281 PyErr_Format(PyExc_TypeError,
14282 "%%%c format: a number is required, "
14283 "not %.200s",
14284 type, Py_TYPE(v)->tp_name);
14285 break;
14286 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014287 return -1;
14288}
14289
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014290static Py_UCS4
14291formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014292{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014293 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014294 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014295 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014296 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014297 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014298 goto onError;
14299 }
14300 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014301 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014302 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014303 /* make sure number is a type of integer */
14304 if (!PyLong_Check(v)) {
14305 iobj = PyNumber_Index(v);
14306 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014307 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014308 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014309 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014310 Py_DECREF(iobj);
14311 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014312 else {
14313 x = PyLong_AsLong(v);
14314 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014315 if (x == -1 && PyErr_Occurred())
14316 goto onError;
14317
Victor Stinner8faf8212011-12-08 22:14:11 +010014318 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014319 PyErr_SetString(PyExc_OverflowError,
14320 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014321 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014322 }
14323
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014324 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014325 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014326
Benjamin Peterson29060642009-01-31 22:14:21 +000014327 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014328 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014329 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014330 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014331}
14332
Victor Stinnera47082312012-10-04 02:19:54 +020014333/* Parse options of an argument: flags, width, precision.
14334 Handle also "%(name)" syntax.
14335
14336 Return 0 if the argument has been formatted into arg->str.
14337 Return 1 if the argument has been written into ctx->writer,
14338 Raise an exception and return -1 on error. */
14339static int
14340unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14341 struct unicode_format_arg_t *arg)
14342{
14343#define FORMAT_READ(ctx) \
14344 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14345
14346 PyObject *v;
14347
Victor Stinnera47082312012-10-04 02:19:54 +020014348 if (arg->ch == '(') {
14349 /* Get argument value from a dictionary. Example: "%(name)s". */
14350 Py_ssize_t keystart;
14351 Py_ssize_t keylen;
14352 PyObject *key;
14353 int pcount = 1;
14354
14355 if (ctx->dict == NULL) {
14356 PyErr_SetString(PyExc_TypeError,
14357 "format requires a mapping");
14358 return -1;
14359 }
14360 ++ctx->fmtpos;
14361 --ctx->fmtcnt;
14362 keystart = ctx->fmtpos;
14363 /* Skip over balanced parentheses */
14364 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14365 arg->ch = FORMAT_READ(ctx);
14366 if (arg->ch == ')')
14367 --pcount;
14368 else if (arg->ch == '(')
14369 ++pcount;
14370 ctx->fmtpos++;
14371 }
14372 keylen = ctx->fmtpos - keystart - 1;
14373 if (ctx->fmtcnt < 0 || pcount > 0) {
14374 PyErr_SetString(PyExc_ValueError,
14375 "incomplete format key");
14376 return -1;
14377 }
14378 key = PyUnicode_Substring(ctx->fmtstr,
14379 keystart, keystart + keylen);
14380 if (key == NULL)
14381 return -1;
14382 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014383 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014384 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014385 }
14386 ctx->args = PyObject_GetItem(ctx->dict, key);
14387 Py_DECREF(key);
14388 if (ctx->args == NULL)
14389 return -1;
14390 ctx->args_owned = 1;
14391 ctx->arglen = -1;
14392 ctx->argidx = -2;
14393 }
14394
14395 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014396 while (--ctx->fmtcnt >= 0) {
14397 arg->ch = FORMAT_READ(ctx);
14398 ctx->fmtpos++;
14399 switch (arg->ch) {
14400 case '-': arg->flags |= F_LJUST; continue;
14401 case '+': arg->flags |= F_SIGN; continue;
14402 case ' ': arg->flags |= F_BLANK; continue;
14403 case '#': arg->flags |= F_ALT; continue;
14404 case '0': arg->flags |= F_ZERO; continue;
14405 }
14406 break;
14407 }
14408
14409 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014410 if (arg->ch == '*') {
14411 v = unicode_format_getnextarg(ctx);
14412 if (v == NULL)
14413 return -1;
14414 if (!PyLong_Check(v)) {
14415 PyErr_SetString(PyExc_TypeError,
14416 "* wants int");
14417 return -1;
14418 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014419 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014420 if (arg->width == -1 && PyErr_Occurred())
14421 return -1;
14422 if (arg->width < 0) {
14423 arg->flags |= F_LJUST;
14424 arg->width = -arg->width;
14425 }
14426 if (--ctx->fmtcnt >= 0) {
14427 arg->ch = FORMAT_READ(ctx);
14428 ctx->fmtpos++;
14429 }
14430 }
14431 else if (arg->ch >= '0' && arg->ch <= '9') {
14432 arg->width = arg->ch - '0';
14433 while (--ctx->fmtcnt >= 0) {
14434 arg->ch = FORMAT_READ(ctx);
14435 ctx->fmtpos++;
14436 if (arg->ch < '0' || arg->ch > '9')
14437 break;
14438 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14439 mixing signed and unsigned comparison. Since arg->ch is between
14440 '0' and '9', casting to int is safe. */
14441 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14442 PyErr_SetString(PyExc_ValueError,
14443 "width too big");
14444 return -1;
14445 }
14446 arg->width = arg->width*10 + (arg->ch - '0');
14447 }
14448 }
14449
14450 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014451 if (arg->ch == '.') {
14452 arg->prec = 0;
14453 if (--ctx->fmtcnt >= 0) {
14454 arg->ch = FORMAT_READ(ctx);
14455 ctx->fmtpos++;
14456 }
14457 if (arg->ch == '*') {
14458 v = unicode_format_getnextarg(ctx);
14459 if (v == NULL)
14460 return -1;
14461 if (!PyLong_Check(v)) {
14462 PyErr_SetString(PyExc_TypeError,
14463 "* wants int");
14464 return -1;
14465 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014466 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014467 if (arg->prec == -1 && PyErr_Occurred())
14468 return -1;
14469 if (arg->prec < 0)
14470 arg->prec = 0;
14471 if (--ctx->fmtcnt >= 0) {
14472 arg->ch = FORMAT_READ(ctx);
14473 ctx->fmtpos++;
14474 }
14475 }
14476 else if (arg->ch >= '0' && arg->ch <= '9') {
14477 arg->prec = arg->ch - '0';
14478 while (--ctx->fmtcnt >= 0) {
14479 arg->ch = FORMAT_READ(ctx);
14480 ctx->fmtpos++;
14481 if (arg->ch < '0' || arg->ch > '9')
14482 break;
14483 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14484 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014485 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014486 return -1;
14487 }
14488 arg->prec = arg->prec*10 + (arg->ch - '0');
14489 }
14490 }
14491 }
14492
14493 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14494 if (ctx->fmtcnt >= 0) {
14495 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14496 if (--ctx->fmtcnt >= 0) {
14497 arg->ch = FORMAT_READ(ctx);
14498 ctx->fmtpos++;
14499 }
14500 }
14501 }
14502 if (ctx->fmtcnt < 0) {
14503 PyErr_SetString(PyExc_ValueError,
14504 "incomplete format");
14505 return -1;
14506 }
14507 return 0;
14508
14509#undef FORMAT_READ
14510}
14511
14512/* Format one argument. Supported conversion specifiers:
14513
14514 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014515 - "i", "d", "u": int or float
14516 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014517 - "e", "E", "f", "F", "g", "G": float
14518 - "c": int or str (1 character)
14519
Victor Stinner8dbd4212012-12-04 09:30:24 +010014520 When possible, the output is written directly into the Unicode writer
14521 (ctx->writer). A string is created when padding is required.
14522
Victor Stinnera47082312012-10-04 02:19:54 +020014523 Return 0 if the argument has been formatted into *p_str,
14524 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014525 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014526static int
14527unicode_format_arg_format(struct unicode_formatter_t *ctx,
14528 struct unicode_format_arg_t *arg,
14529 PyObject **p_str)
14530{
14531 PyObject *v;
14532 _PyUnicodeWriter *writer = &ctx->writer;
14533
14534 if (ctx->fmtcnt == 0)
14535 ctx->writer.overallocate = 0;
14536
Victor Stinnera47082312012-10-04 02:19:54 +020014537 v = unicode_format_getnextarg(ctx);
14538 if (v == NULL)
14539 return -1;
14540
Victor Stinnera47082312012-10-04 02:19:54 +020014541
14542 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014543 case 's':
14544 case 'r':
14545 case 'a':
14546 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14547 /* Fast path */
14548 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14549 return -1;
14550 return 1;
14551 }
14552
14553 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14554 *p_str = v;
14555 Py_INCREF(*p_str);
14556 }
14557 else {
14558 if (arg->ch == 's')
14559 *p_str = PyObject_Str(v);
14560 else if (arg->ch == 'r')
14561 *p_str = PyObject_Repr(v);
14562 else
14563 *p_str = PyObject_ASCII(v);
14564 }
14565 break;
14566
14567 case 'i':
14568 case 'd':
14569 case 'u':
14570 case 'o':
14571 case 'x':
14572 case 'X':
14573 {
14574 int ret = mainformatlong(v, arg, p_str, writer);
14575 if (ret != 0)
14576 return ret;
14577 arg->sign = 1;
14578 break;
14579 }
14580
14581 case 'e':
14582 case 'E':
14583 case 'f':
14584 case 'F':
14585 case 'g':
14586 case 'G':
14587 if (arg->width == -1 && arg->prec == -1
14588 && !(arg->flags & (F_SIGN | F_BLANK)))
14589 {
14590 /* Fast path */
14591 if (formatfloat(v, arg, NULL, writer) == -1)
14592 return -1;
14593 return 1;
14594 }
14595
14596 arg->sign = 1;
14597 if (formatfloat(v, arg, p_str, NULL) == -1)
14598 return -1;
14599 break;
14600
14601 case 'c':
14602 {
14603 Py_UCS4 ch = formatchar(v);
14604 if (ch == (Py_UCS4) -1)
14605 return -1;
14606 if (arg->width == -1 && arg->prec == -1) {
14607 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014608 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014609 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014610 return 1;
14611 }
14612 *p_str = PyUnicode_FromOrdinal(ch);
14613 break;
14614 }
14615
14616 default:
14617 PyErr_Format(PyExc_ValueError,
14618 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014619 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014620 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14621 (int)arg->ch,
14622 ctx->fmtpos - 1);
14623 return -1;
14624 }
14625 if (*p_str == NULL)
14626 return -1;
14627 assert (PyUnicode_Check(*p_str));
14628 return 0;
14629}
14630
14631static int
14632unicode_format_arg_output(struct unicode_formatter_t *ctx,
14633 struct unicode_format_arg_t *arg,
14634 PyObject *str)
14635{
14636 Py_ssize_t len;
14637 enum PyUnicode_Kind kind;
14638 void *pbuf;
14639 Py_ssize_t pindex;
14640 Py_UCS4 signchar;
14641 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014642 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014643 Py_ssize_t sublen;
14644 _PyUnicodeWriter *writer = &ctx->writer;
14645 Py_UCS4 fill;
14646
14647 fill = ' ';
14648 if (arg->sign && arg->flags & F_ZERO)
14649 fill = '0';
14650
14651 if (PyUnicode_READY(str) == -1)
14652 return -1;
14653
14654 len = PyUnicode_GET_LENGTH(str);
14655 if ((arg->width == -1 || arg->width <= len)
14656 && (arg->prec == -1 || arg->prec >= len)
14657 && !(arg->flags & (F_SIGN | F_BLANK)))
14658 {
14659 /* Fast path */
14660 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14661 return -1;
14662 return 0;
14663 }
14664
14665 /* Truncate the string for "s", "r" and "a" formats
14666 if the precision is set */
14667 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14668 if (arg->prec >= 0 && len > arg->prec)
14669 len = arg->prec;
14670 }
14671
14672 /* Adjust sign and width */
14673 kind = PyUnicode_KIND(str);
14674 pbuf = PyUnicode_DATA(str);
14675 pindex = 0;
14676 signchar = '\0';
14677 if (arg->sign) {
14678 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14679 if (ch == '-' || ch == '+') {
14680 signchar = ch;
14681 len--;
14682 pindex++;
14683 }
14684 else if (arg->flags & F_SIGN)
14685 signchar = '+';
14686 else if (arg->flags & F_BLANK)
14687 signchar = ' ';
14688 else
14689 arg->sign = 0;
14690 }
14691 if (arg->width < len)
14692 arg->width = len;
14693
14694 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014695 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014696 if (!(arg->flags & F_LJUST)) {
14697 if (arg->sign) {
14698 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014699 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014700 }
14701 else {
14702 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014703 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014704 }
14705 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014706 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14707 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014708 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014709 }
14710
Victor Stinnera47082312012-10-04 02:19:54 +020014711 buflen = arg->width;
14712 if (arg->sign && len == arg->width)
14713 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014714 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014715 return -1;
14716
14717 /* Write the sign if needed */
14718 if (arg->sign) {
14719 if (fill != ' ') {
14720 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14721 writer->pos += 1;
14722 }
14723 if (arg->width > len)
14724 arg->width--;
14725 }
14726
14727 /* Write the numeric prefix for "x", "X" and "o" formats
14728 if the alternate form is used.
14729 For example, write "0x" for the "%#x" format. */
14730 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14731 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14732 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14733 if (fill != ' ') {
14734 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14735 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14736 writer->pos += 2;
14737 pindex += 2;
14738 }
14739 arg->width -= 2;
14740 if (arg->width < 0)
14741 arg->width = 0;
14742 len -= 2;
14743 }
14744
14745 /* Pad left with the fill character if needed */
14746 if (arg->width > len && !(arg->flags & F_LJUST)) {
14747 sublen = arg->width - len;
14748 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14749 writer->pos += sublen;
14750 arg->width = len;
14751 }
14752
14753 /* If padding with spaces: write sign if needed and/or numeric prefix if
14754 the alternate form is used */
14755 if (fill == ' ') {
14756 if (arg->sign) {
14757 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14758 writer->pos += 1;
14759 }
14760 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14761 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14762 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14763 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14764 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14765 writer->pos += 2;
14766 pindex += 2;
14767 }
14768 }
14769
14770 /* Write characters */
14771 if (len) {
14772 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14773 str, pindex, len);
14774 writer->pos += len;
14775 }
14776
14777 /* Pad right with the fill character if needed */
14778 if (arg->width > len) {
14779 sublen = arg->width - len;
14780 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14781 writer->pos += sublen;
14782 }
14783 return 0;
14784}
14785
14786/* Helper of PyUnicode_Format(): format one arg.
14787 Return 0 on success, raise an exception and return -1 on error. */
14788static int
14789unicode_format_arg(struct unicode_formatter_t *ctx)
14790{
14791 struct unicode_format_arg_t arg;
14792 PyObject *str;
14793 int ret;
14794
Victor Stinner8dbd4212012-12-04 09:30:24 +010014795 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014796 if (arg.ch == '%') {
14797 ctx->fmtpos++;
14798 ctx->fmtcnt--;
14799 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14800 return -1;
14801 return 0;
14802 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014803 arg.flags = 0;
14804 arg.width = -1;
14805 arg.prec = -1;
14806 arg.sign = 0;
14807 str = NULL;
14808
Victor Stinnera47082312012-10-04 02:19:54 +020014809 ret = unicode_format_arg_parse(ctx, &arg);
14810 if (ret == -1)
14811 return -1;
14812
14813 ret = unicode_format_arg_format(ctx, &arg, &str);
14814 if (ret == -1)
14815 return -1;
14816
14817 if (ret != 1) {
14818 ret = unicode_format_arg_output(ctx, &arg, str);
14819 Py_DECREF(str);
14820 if (ret == -1)
14821 return -1;
14822 }
14823
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014824 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014825 PyErr_SetString(PyExc_TypeError,
14826 "not all arguments converted during string formatting");
14827 return -1;
14828 }
14829 return 0;
14830}
14831
Alexander Belopolsky40018472011-02-26 01:02:56 +000014832PyObject *
14833PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014834{
Victor Stinnera47082312012-10-04 02:19:54 +020014835 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014836
Guido van Rossumd57fd912000-03-10 22:53:23 +000014837 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014838 PyErr_BadInternalCall();
14839 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014840 }
Victor Stinnera47082312012-10-04 02:19:54 +020014841
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014842 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014843 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014844
14845 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014846 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14847 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14848 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14849 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014850
Victor Stinner8f674cc2013-04-17 23:02:17 +020014851 _PyUnicodeWriter_Init(&ctx.writer);
14852 ctx.writer.min_length = ctx.fmtcnt + 100;
14853 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014854
Guido van Rossumd57fd912000-03-10 22:53:23 +000014855 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014856 ctx.arglen = PyTuple_Size(args);
14857 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014858 }
14859 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014860 ctx.arglen = -1;
14861 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014862 }
Victor Stinnera47082312012-10-04 02:19:54 +020014863 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014864 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014865 ctx.dict = args;
14866 else
14867 ctx.dict = NULL;
14868 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014869
Victor Stinnera47082312012-10-04 02:19:54 +020014870 while (--ctx.fmtcnt >= 0) {
14871 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014872 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014873
14874 nonfmtpos = ctx.fmtpos++;
14875 while (ctx.fmtcnt >= 0 &&
14876 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14877 ctx.fmtpos++;
14878 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014879 }
Victor Stinnera47082312012-10-04 02:19:54 +020014880 if (ctx.fmtcnt < 0) {
14881 ctx.fmtpos--;
14882 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014883 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014884
Victor Stinnercfc4c132013-04-03 01:48:39 +020014885 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14886 nonfmtpos, ctx.fmtpos) < 0)
14887 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014888 }
14889 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014890 ctx.fmtpos++;
14891 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014892 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014893 }
14894 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014895
Victor Stinnera47082312012-10-04 02:19:54 +020014896 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014897 PyErr_SetString(PyExc_TypeError,
14898 "not all arguments converted during string formatting");
14899 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014900 }
14901
Victor Stinnera47082312012-10-04 02:19:54 +020014902 if (ctx.args_owned) {
14903 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014904 }
Victor Stinnera47082312012-10-04 02:19:54 +020014905 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014906
Benjamin Peterson29060642009-01-31 22:14:21 +000014907 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014908 _PyUnicodeWriter_Dealloc(&ctx.writer);
14909 if (ctx.args_owned) {
14910 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014911 }
14912 return NULL;
14913}
14914
Jeremy Hylton938ace62002-07-17 16:30:39 +000014915static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014916unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14917
Tim Peters6d6c1a32001-08-02 04:15:00 +000014918static PyObject *
14919unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14920{
Benjamin Peterson29060642009-01-31 22:14:21 +000014921 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014922 static char *kwlist[] = {"object", "encoding", "errors", 0};
14923 char *encoding = NULL;
14924 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014925
Benjamin Peterson14339b62009-01-31 16:36:08 +000014926 if (type != &PyUnicode_Type)
14927 return unicode_subtype_new(type, args, kwds);
14928 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014929 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014930 return NULL;
14931 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014932 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014933 if (encoding == NULL && errors == NULL)
14934 return PyObject_Str(x);
14935 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014936 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014937}
14938
Guido van Rossume023fe02001-08-30 03:12:59 +000014939static PyObject *
14940unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14941{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014942 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014943 Py_ssize_t length, char_size;
14944 int share_wstr, share_utf8;
14945 unsigned int kind;
14946 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014947
Benjamin Peterson14339b62009-01-31 16:36:08 +000014948 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014949
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014950 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014951 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014952 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014953 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014954 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014955 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014956 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014957 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014958
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014959 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014960 if (self == NULL) {
14961 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014962 return NULL;
14963 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014964 kind = PyUnicode_KIND(unicode);
14965 length = PyUnicode_GET_LENGTH(unicode);
14966
14967 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014968#ifdef Py_DEBUG
14969 _PyUnicode_HASH(self) = -1;
14970#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014971 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014972#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014973 _PyUnicode_STATE(self).interned = 0;
14974 _PyUnicode_STATE(self).kind = kind;
14975 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014976 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014977 _PyUnicode_STATE(self).ready = 1;
14978 _PyUnicode_WSTR(self) = NULL;
14979 _PyUnicode_UTF8_LENGTH(self) = 0;
14980 _PyUnicode_UTF8(self) = NULL;
14981 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014982 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014983
14984 share_utf8 = 0;
14985 share_wstr = 0;
14986 if (kind == PyUnicode_1BYTE_KIND) {
14987 char_size = 1;
14988 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14989 share_utf8 = 1;
14990 }
14991 else if (kind == PyUnicode_2BYTE_KIND) {
14992 char_size = 2;
14993 if (sizeof(wchar_t) == 2)
14994 share_wstr = 1;
14995 }
14996 else {
14997 assert(kind == PyUnicode_4BYTE_KIND);
14998 char_size = 4;
14999 if (sizeof(wchar_t) == 4)
15000 share_wstr = 1;
15001 }
15002
15003 /* Ensure we won't overflow the length. */
15004 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15005 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015006 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015007 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015008 data = PyObject_MALLOC((length + 1) * char_size);
15009 if (data == NULL) {
15010 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015011 goto onError;
15012 }
15013
Victor Stinnerc3c74152011-10-02 20:39:55 +020015014 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015015 if (share_utf8) {
15016 _PyUnicode_UTF8_LENGTH(self) = length;
15017 _PyUnicode_UTF8(self) = data;
15018 }
15019 if (share_wstr) {
15020 _PyUnicode_WSTR_LENGTH(self) = length;
15021 _PyUnicode_WSTR(self) = (wchar_t *)data;
15022 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015023
Christian Heimesf051e432016-09-13 20:22:02 +020015024 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015025 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015026 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015027#ifdef Py_DEBUG
15028 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15029#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015030 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015031 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015032
15033onError:
15034 Py_DECREF(unicode);
15035 Py_DECREF(self);
15036 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015037}
15038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015039PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015040"str(object='') -> str\n\
15041str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015042\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015043Create a new string object from the given object. If encoding or\n\
15044errors is specified, then the object must expose a data buffer\n\
15045that will be decoded using the given encoding and error handler.\n\
15046Otherwise, returns the result of object.__str__() (if defined)\n\
15047or repr(object).\n\
15048encoding defaults to sys.getdefaultencoding().\n\
15049errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015050
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015051static PyObject *unicode_iter(PyObject *seq);
15052
Guido van Rossumd57fd912000-03-10 22:53:23 +000015053PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015054 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015055 "str", /* tp_name */
15056 sizeof(PyUnicodeObject), /* tp_size */
15057 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015058 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015059 (destructor)unicode_dealloc, /* tp_dealloc */
15060 0, /* tp_print */
15061 0, /* tp_getattr */
15062 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015063 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015064 unicode_repr, /* tp_repr */
15065 &unicode_as_number, /* tp_as_number */
15066 &unicode_as_sequence, /* tp_as_sequence */
15067 &unicode_as_mapping, /* tp_as_mapping */
15068 (hashfunc) unicode_hash, /* tp_hash*/
15069 0, /* tp_call*/
15070 (reprfunc) unicode_str, /* tp_str */
15071 PyObject_GenericGetAttr, /* tp_getattro */
15072 0, /* tp_setattro */
15073 0, /* tp_as_buffer */
15074 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015075 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015076 unicode_doc, /* tp_doc */
15077 0, /* tp_traverse */
15078 0, /* tp_clear */
15079 PyUnicode_RichCompare, /* tp_richcompare */
15080 0, /* tp_weaklistoffset */
15081 unicode_iter, /* tp_iter */
15082 0, /* tp_iternext */
15083 unicode_methods, /* tp_methods */
15084 0, /* tp_members */
15085 0, /* tp_getset */
15086 &PyBaseObject_Type, /* tp_base */
15087 0, /* tp_dict */
15088 0, /* tp_descr_get */
15089 0, /* tp_descr_set */
15090 0, /* tp_dictoffset */
15091 0, /* tp_init */
15092 0, /* tp_alloc */
15093 unicode_new, /* tp_new */
15094 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015095};
15096
15097/* Initialize the Unicode implementation */
15098
Victor Stinner3a50e702011-10-18 21:21:00 +020015099int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015100{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015101 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015102 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015103 0x000A, /* LINE FEED */
15104 0x000D, /* CARRIAGE RETURN */
15105 0x001C, /* FILE SEPARATOR */
15106 0x001D, /* GROUP SEPARATOR */
15107 0x001E, /* RECORD SEPARATOR */
15108 0x0085, /* NEXT LINE */
15109 0x2028, /* LINE SEPARATOR */
15110 0x2029, /* PARAGRAPH SEPARATOR */
15111 };
15112
Fred Drakee4315f52000-05-09 19:53:39 +000015113 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015114 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015115 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015116 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015117 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015118
Guido van Rossumcacfc072002-05-24 19:01:59 +000015119 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015120 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015121
15122 /* initialize the linebreak bloom filter */
15123 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015124 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015125 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015126
Christian Heimes26532f72013-07-20 14:57:16 +020015127 if (PyType_Ready(&EncodingMapType) < 0)
15128 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015129
Benjamin Petersonc4311282012-10-30 23:21:10 -040015130 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15131 Py_FatalError("Can't initialize field name iterator type");
15132
15133 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15134 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015135
Victor Stinner3a50e702011-10-18 21:21:00 +020015136 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015137}
15138
15139/* Finalize the Unicode implementation */
15140
Christian Heimesa156e092008-02-16 07:38:31 +000015141int
15142PyUnicode_ClearFreeList(void)
15143{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015144 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015145}
15146
Guido van Rossumd57fd912000-03-10 22:53:23 +000015147void
Thomas Wouters78890102000-07-22 19:25:51 +000015148_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015149{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015150 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015151
Serhiy Storchaka05997252013-01-26 12:14:02 +020015152 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015153
Serhiy Storchaka05997252013-01-26 12:14:02 +020015154 for (i = 0; i < 256; i++)
15155 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015156 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015157 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015158}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015159
Walter Dörwald16807132007-05-25 13:52:07 +000015160void
15161PyUnicode_InternInPlace(PyObject **p)
15162{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015163 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015164 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015165#ifdef Py_DEBUG
15166 assert(s != NULL);
15167 assert(_PyUnicode_CHECK(s));
15168#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015169 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015170 return;
15171#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015172 /* If it's a subclass, we don't really know what putting
15173 it in the interned dict might do. */
15174 if (!PyUnicode_CheckExact(s))
15175 return;
15176 if (PyUnicode_CHECK_INTERNED(s))
15177 return;
15178 if (interned == NULL) {
15179 interned = PyDict_New();
15180 if (interned == NULL) {
15181 PyErr_Clear(); /* Don't leave an exception */
15182 return;
15183 }
15184 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015185 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015186 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015187 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015188 if (t == NULL) {
15189 PyErr_Clear();
15190 return;
15191 }
15192 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015193 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015194 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015195 return;
15196 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015197 /* The two references in interned are not counted by refcnt.
15198 The deallocator will take care of this */
15199 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015200 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015201}
15202
15203void
15204PyUnicode_InternImmortal(PyObject **p)
15205{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015206 PyUnicode_InternInPlace(p);
15207 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015208 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015209 Py_INCREF(*p);
15210 }
Walter Dörwald16807132007-05-25 13:52:07 +000015211}
15212
15213PyObject *
15214PyUnicode_InternFromString(const char *cp)
15215{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015216 PyObject *s = PyUnicode_FromString(cp);
15217 if (s == NULL)
15218 return NULL;
15219 PyUnicode_InternInPlace(&s);
15220 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015221}
15222
Alexander Belopolsky40018472011-02-26 01:02:56 +000015223void
15224_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015225{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015226 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015227 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015228 Py_ssize_t i, n;
15229 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015230
Benjamin Peterson14339b62009-01-31 16:36:08 +000015231 if (interned == NULL || !PyDict_Check(interned))
15232 return;
15233 keys = PyDict_Keys(interned);
15234 if (keys == NULL || !PyList_Check(keys)) {
15235 PyErr_Clear();
15236 return;
15237 }
Walter Dörwald16807132007-05-25 13:52:07 +000015238
Benjamin Peterson14339b62009-01-31 16:36:08 +000015239 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15240 detector, interned unicode strings are not forcibly deallocated;
15241 rather, we give them their stolen references back, and then clear
15242 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015243
Benjamin Peterson14339b62009-01-31 16:36:08 +000015244 n = PyList_GET_SIZE(keys);
15245 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015246 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015247 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015248 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015249 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015250 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015252 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015253 case SSTATE_NOT_INTERNED:
15254 /* XXX Shouldn't happen */
15255 break;
15256 case SSTATE_INTERNED_IMMORTAL:
15257 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015258 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 break;
15260 case SSTATE_INTERNED_MORTAL:
15261 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015262 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015263 break;
15264 default:
15265 Py_FatalError("Inconsistent interned string state.");
15266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015267 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 }
15269 fprintf(stderr, "total size of all interned strings: "
15270 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15271 "mortal/immortal\n", mortal_size, immortal_size);
15272 Py_DECREF(keys);
15273 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015274 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015275}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015276
15277
15278/********************* Unicode Iterator **************************/
15279
15280typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015281 PyObject_HEAD
15282 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015283 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015284} unicodeiterobject;
15285
15286static void
15287unicodeiter_dealloc(unicodeiterobject *it)
15288{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015289 _PyObject_GC_UNTRACK(it);
15290 Py_XDECREF(it->it_seq);
15291 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015292}
15293
15294static int
15295unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15296{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015297 Py_VISIT(it->it_seq);
15298 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015299}
15300
15301static PyObject *
15302unicodeiter_next(unicodeiterobject *it)
15303{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015304 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015305
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 assert(it != NULL);
15307 seq = it->it_seq;
15308 if (seq == NULL)
15309 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015310 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015312 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15313 int kind = PyUnicode_KIND(seq);
15314 void *data = PyUnicode_DATA(seq);
15315 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15316 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015317 if (item != NULL)
15318 ++it->it_index;
15319 return item;
15320 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015321
Benjamin Peterson14339b62009-01-31 16:36:08 +000015322 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015323 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015324 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015325}
15326
15327static PyObject *
15328unicodeiter_len(unicodeiterobject *it)
15329{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015330 Py_ssize_t len = 0;
15331 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015332 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015333 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015334}
15335
15336PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15337
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015338static PyObject *
15339unicodeiter_reduce(unicodeiterobject *it)
15340{
15341 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015342 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015343 it->it_seq, it->it_index);
15344 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015345 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015346 if (u == NULL)
15347 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015348 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015349 }
15350}
15351
15352PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15353
15354static PyObject *
15355unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15356{
15357 Py_ssize_t index = PyLong_AsSsize_t(state);
15358 if (index == -1 && PyErr_Occurred())
15359 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015360 if (it->it_seq != NULL) {
15361 if (index < 0)
15362 index = 0;
15363 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15364 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15365 it->it_index = index;
15366 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015367 Py_RETURN_NONE;
15368}
15369
15370PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15371
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015372static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015373 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015374 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015375 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15376 reduce_doc},
15377 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15378 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015379 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015380};
15381
15382PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015383 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15384 "str_iterator", /* tp_name */
15385 sizeof(unicodeiterobject), /* tp_basicsize */
15386 0, /* tp_itemsize */
15387 /* methods */
15388 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15389 0, /* tp_print */
15390 0, /* tp_getattr */
15391 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015392 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015393 0, /* tp_repr */
15394 0, /* tp_as_number */
15395 0, /* tp_as_sequence */
15396 0, /* tp_as_mapping */
15397 0, /* tp_hash */
15398 0, /* tp_call */
15399 0, /* tp_str */
15400 PyObject_GenericGetAttr, /* tp_getattro */
15401 0, /* tp_setattro */
15402 0, /* tp_as_buffer */
15403 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15404 0, /* tp_doc */
15405 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15406 0, /* tp_clear */
15407 0, /* tp_richcompare */
15408 0, /* tp_weaklistoffset */
15409 PyObject_SelfIter, /* tp_iter */
15410 (iternextfunc)unicodeiter_next, /* tp_iternext */
15411 unicodeiter_methods, /* tp_methods */
15412 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015413};
15414
15415static PyObject *
15416unicode_iter(PyObject *seq)
15417{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015418 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015419
Benjamin Peterson14339b62009-01-31 16:36:08 +000015420 if (!PyUnicode_Check(seq)) {
15421 PyErr_BadInternalCall();
15422 return NULL;
15423 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015424 if (PyUnicode_READY(seq) == -1)
15425 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015426 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15427 if (it == NULL)
15428 return NULL;
15429 it->it_index = 0;
15430 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015431 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015432 _PyObject_GC_TRACK(it);
15433 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015434}
15435
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015436
15437size_t
15438Py_UNICODE_strlen(const Py_UNICODE *u)
15439{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015440 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015441}
15442
15443Py_UNICODE*
15444Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15445{
15446 Py_UNICODE *u = s1;
15447 while ((*u++ = *s2++));
15448 return s1;
15449}
15450
15451Py_UNICODE*
15452Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15453{
15454 Py_UNICODE *u = s1;
15455 while ((*u++ = *s2++))
15456 if (n-- == 0)
15457 break;
15458 return s1;
15459}
15460
15461Py_UNICODE*
15462Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15463{
15464 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015465 u1 += wcslen(u1);
15466 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015467 return s1;
15468}
15469
15470int
15471Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15472{
15473 while (*s1 && *s2 && *s1 == *s2)
15474 s1++, s2++;
15475 if (*s1 && *s2)
15476 return (*s1 < *s2) ? -1 : +1;
15477 if (*s1)
15478 return 1;
15479 if (*s2)
15480 return -1;
15481 return 0;
15482}
15483
15484int
15485Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15486{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015487 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015488 for (; n != 0; n--) {
15489 u1 = *s1;
15490 u2 = *s2;
15491 if (u1 != u2)
15492 return (u1 < u2) ? -1 : +1;
15493 if (u1 == '\0')
15494 return 0;
15495 s1++;
15496 s2++;
15497 }
15498 return 0;
15499}
15500
15501Py_UNICODE*
15502Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15503{
15504 const Py_UNICODE *p;
15505 for (p = s; *p; p++)
15506 if (*p == c)
15507 return (Py_UNICODE*)p;
15508 return NULL;
15509}
15510
15511Py_UNICODE*
15512Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15513{
15514 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015515 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015516 while (p != s) {
15517 p--;
15518 if (*p == c)
15519 return (Py_UNICODE*)p;
15520 }
15521 return NULL;
15522}
Victor Stinner331ea922010-08-10 16:37:20 +000015523
Victor Stinner71133ff2010-09-01 23:43:53 +000015524Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015525PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015526{
Victor Stinner577db2c2011-10-11 22:12:48 +020015527 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015528 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015529
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015530 if (!PyUnicode_Check(unicode)) {
15531 PyErr_BadArgument();
15532 return NULL;
15533 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015534 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015535 if (u == NULL)
15536 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015537 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015538 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015539 PyErr_NoMemory();
15540 return NULL;
15541 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015542 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015543 size *= sizeof(Py_UNICODE);
15544 copy = PyMem_Malloc(size);
15545 if (copy == NULL) {
15546 PyErr_NoMemory();
15547 return NULL;
15548 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015549 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015550 return copy;
15551}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015552
Georg Brandl66c221e2010-10-14 07:04:07 +000015553/* A _string module, to export formatter_parser and formatter_field_name_split
15554 to the string.Formatter class implemented in Python. */
15555
15556static PyMethodDef _string_methods[] = {
15557 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15558 METH_O, PyDoc_STR("split the argument as a field name")},
15559 {"formatter_parser", (PyCFunction) formatter_parser,
15560 METH_O, PyDoc_STR("parse the argument as a format string")},
15561 {NULL, NULL}
15562};
15563
15564static struct PyModuleDef _string_module = {
15565 PyModuleDef_HEAD_INIT,
15566 "_string",
15567 PyDoc_STR("string helper module"),
15568 0,
15569 _string_methods,
15570 NULL,
15571 NULL,
15572 NULL,
15573 NULL
15574};
15575
15576PyMODINIT_FUNC
15577PyInit__string(void)
15578{
15579 return PyModule_Create(&_string_module);
15580}
15581
15582
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015583#ifdef __cplusplus
15584}
15585#endif