blob: 5d605abd0327c508a165e66d2d84f0c9f0cb7a8f [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 Stinner1b579672011-12-17 05:47:23 +01003330static int
3331locale_error_handler(const char *errors, int *surrogateescape)
3332{
Victor Stinner50149202015-09-22 00:26:54 +02003333 _Py_error_handler error_handler = get_error_handler(errors);
3334 switch (error_handler)
3335 {
3336 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003337 *surrogateescape = 0;
3338 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003339 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003340 *surrogateescape = 1;
3341 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003342 default:
3343 PyErr_Format(PyExc_ValueError,
3344 "only 'strict' and 'surrogateescape' error handlers "
3345 "are supported, not '%s'",
3346 errors);
3347 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003348 }
Victor Stinner1b579672011-12-17 05:47:23 +01003349}
3350
Victor Stinner2cba6b82018-01-10 22:46:15 +01003351static PyObject *
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003352unicode_encode_locale(PyObject *unicode, const char *errors,
3353 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003354{
Victor Stinner1b579672011-12-17 05:47:23 +01003355 int surrogateescape;
Victor Stinner1b579672011-12-17 05:47:23 +01003356 if (locale_error_handler(errors, &surrogateescape) < 0)
3357 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003358
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003359 Py_ssize_t wlen;
3360 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3361 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003362 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003363 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003364
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003365 Py_ssize_t wlen2 = wcslen(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003366 if (wlen2 != wlen) {
3367 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003368 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003369 return NULL;
3370 }
3371
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003372 char *str;
3373 size_t error_pos;
3374 const char *reason;
3375 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
3376 current_locale, surrogateescape);
3377 if (res != 0) {
3378 if (res == -2) {
3379 PyObject *exc;
3380 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3381 "locale", unicode,
3382 (Py_ssize_t)error_pos,
3383 (Py_ssize_t)(error_pos+1),
3384 reason);
3385 if (exc != NULL) {
3386 PyCodec_StrictErrors(exc);
3387 Py_DECREF(exc);
3388 }
3389 return NULL;
Victor Stinner2cba6b82018-01-10 22:46:15 +01003390 }
3391 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003392 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003393 PyMem_Free(wstr);
3394 return NULL;
3395 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003396 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003397 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003399 PyObject *bytes = PyBytes_FromString(str);
3400 PyMem_RawFree(str);
3401 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003402}
3403
Victor Stinnerad158722010-10-27 00:25:46 +00003404PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003405PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3406{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003407 return unicode_encode_locale(unicode, errors, 1);
3408}
3409
3410PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003411PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003412{
Steve Dowercc16be82016-09-08 10:35:16 -07003413#if defined(__APPLE__)
3414 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003415#else
Victor Stinner793b5312011-04-27 00:24:21 +02003416 PyInterpreterState *interp = PyThreadState_GET()->interp;
3417 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3418 cannot use it to encode and decode filenames before it is loaded. Load
3419 the Python codec requires to encode at least its own filename. Use the C
3420 version of the locale codec until the codec registry is initialized and
3421 the Python codec is loaded.
3422
3423 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3424 cannot only rely on it: check also interp->fscodec_initialized for
3425 subinterpreters. */
3426 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003427 return PyUnicode_AsEncodedString(unicode,
3428 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003429 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003430 }
3431 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003432 return unicode_encode_locale(unicode,
3433 Py_FileSystemDefaultEncodeErrors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003434 }
Victor Stinnerad158722010-10-27 00:25:46 +00003435#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003436}
3437
Alexander Belopolsky40018472011-02-26 01:02:56 +00003438PyObject *
3439PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003440 const char *encoding,
3441 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003442{
3443 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003444 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003445
Guido van Rossumd57fd912000-03-10 22:53:23 +00003446 if (!PyUnicode_Check(unicode)) {
3447 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003448 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003449 }
Fred Drakee4315f52000-05-09 19:53:39 +00003450
Victor Stinner942889a2016-09-05 15:40:10 -07003451 if (encoding == NULL) {
3452 return _PyUnicode_AsUTF8String(unicode, errors);
3453 }
3454
Fred Drakee4315f52000-05-09 19:53:39 +00003455 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003456 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3457 char *lower = buflower;
3458
3459 /* Fast paths */
3460 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3461 lower += 3;
3462 if (*lower == '_') {
3463 /* Match "utf8" and "utf_8" */
3464 lower++;
3465 }
3466
3467 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003468 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003469 }
3470 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3471 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3472 }
3473 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3474 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3475 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003476 }
Victor Stinner942889a2016-09-05 15:40:10 -07003477 else {
3478 if (strcmp(lower, "ascii") == 0
3479 || strcmp(lower, "us_ascii") == 0) {
3480 return _PyUnicode_AsASCIIString(unicode, errors);
3481 }
Steve Dowercc16be82016-09-08 10:35:16 -07003482#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003483 else if (strcmp(lower, "mbcs") == 0) {
3484 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3485 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003486#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003487 else if (strcmp(lower, "latin1") == 0 ||
3488 strcmp(lower, "latin_1") == 0 ||
3489 strcmp(lower, "iso_8859_1") == 0 ||
3490 strcmp(lower, "iso8859_1") == 0) {
3491 return _PyUnicode_AsLatin1String(unicode, errors);
3492 }
3493 }
Victor Stinner37296e82010-06-10 13:36:23 +00003494 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003495
3496 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003497 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003498 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003499 return NULL;
3500
3501 /* The normal path */
3502 if (PyBytes_Check(v))
3503 return v;
3504
3505 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003506 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003507 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003508 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003509
3510 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003511 "encoder %s returned bytearray instead of bytes; "
3512 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003513 encoding);
3514 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003515 Py_DECREF(v);
3516 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003517 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003518
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003519 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3520 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003521 Py_DECREF(v);
3522 return b;
3523 }
3524
3525 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003526 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3527 "use codecs.encode() to encode to arbitrary types",
3528 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003529 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003530 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003531 return NULL;
3532}
3533
Alexander Belopolsky40018472011-02-26 01:02:56 +00003534PyObject *
3535PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003536 const char *encoding,
3537 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003538{
3539 PyObject *v;
3540
3541 if (!PyUnicode_Check(unicode)) {
3542 PyErr_BadArgument();
3543 goto onError;
3544 }
3545
Serhiy Storchaka00939072016-10-27 21:05:49 +03003546 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3547 "PyUnicode_AsEncodedUnicode() is deprecated; "
3548 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3549 return NULL;
3550
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003551 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003552 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003553
3554 /* Encode via the codec registry */
3555 v = PyCodec_Encode(unicode, encoding, errors);
3556 if (v == NULL)
3557 goto onError;
3558 if (!PyUnicode_Check(v)) {
3559 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003560 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3561 "use codecs.encode() to encode to arbitrary types",
3562 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003563 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003564 Py_DECREF(v);
3565 goto onError;
3566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003567 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003568
Benjamin Peterson29060642009-01-31 22:14:21 +00003569 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003570 return NULL;
3571}
3572
Victor Stinner2cba6b82018-01-10 22:46:15 +01003573static PyObject*
3574unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3575 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003576{
Victor Stinner1b579672011-12-17 05:47:23 +01003577 int surrogateescape;
Victor Stinner1b579672011-12-17 05:47:23 +01003578 if (locale_error_handler(errors, &surrogateescape) < 0)
3579 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003580
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003581 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3582 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003583 return NULL;
3584 }
3585
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003586 wchar_t *wstr;
3587 size_t wlen;
3588 const char *reason;
3589 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
3590 current_locale, surrogateescape);
3591 if (res != 0) {
3592 if (res == -2) {
3593 PyObject *exc;
3594 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3595 "locale", str, len,
3596 (Py_ssize_t)wlen,
3597 (Py_ssize_t)(wlen + 1),
3598 reason);
3599 if (exc != NULL) {
3600 PyCodec_StrictErrors(exc);
3601 Py_DECREF(exc);
3602 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003603 }
3604 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003605 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003606 }
Victor Stinner2f197072011-12-17 07:08:30 +01003607 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003608 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003609
3610 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3611 PyMem_RawFree(wstr);
3612 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003613}
3614
3615PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003616PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3617 const char *errors)
3618{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003619 return unicode_decode_locale(str, len, errors, 1);
3620}
3621
3622PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003623PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003624{
3625 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003626 return unicode_decode_locale(str, size, errors, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003627}
3628
3629
3630PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003631PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003632 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003633 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3634}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003635
Christian Heimes5894ba72007-11-04 11:43:14 +00003636PyObject*
3637PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3638{
Steve Dowercc16be82016-09-08 10:35:16 -07003639#if defined(__APPLE__)
3640 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003641#else
Victor Stinner793b5312011-04-27 00:24:21 +02003642 PyInterpreterState *interp = PyThreadState_GET()->interp;
3643 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3644 cannot use it to encode and decode filenames before it is loaded. Load
3645 the Python codec requires to encode at least its own filename. Use the C
3646 version of the locale codec until the codec registry is initialized and
3647 the Python codec is loaded.
3648
3649 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3650 cannot only rely on it: check also interp->fscodec_initialized for
3651 subinterpreters. */
3652 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003653 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003654 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003655 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003656 }
3657 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003658 return unicode_decode_locale(s, size,
3659 Py_FileSystemDefaultEncodeErrors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003660 }
Victor Stinnerad158722010-10-27 00:25:46 +00003661#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003662}
3663
Martin v. Löwis011e8422009-05-05 04:43:17 +00003664
3665int
3666PyUnicode_FSConverter(PyObject* arg, void* addr)
3667{
Brett Cannonec6ce872016-09-06 15:50:29 -07003668 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003669 PyObject *output = NULL;
3670 Py_ssize_t size;
3671 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003672 if (arg == NULL) {
3673 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003674 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003675 return 1;
3676 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003677 path = PyOS_FSPath(arg);
3678 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003679 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003680 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003681 if (PyBytes_Check(path)) {
3682 output = path;
3683 }
3684 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3685 output = PyUnicode_EncodeFSDefault(path);
3686 Py_DECREF(path);
3687 if (!output) {
3688 return 0;
3689 }
3690 assert(PyBytes_Check(output));
3691 }
3692
Victor Stinner0ea2a462010-04-30 00:22:08 +00003693 size = PyBytes_GET_SIZE(output);
3694 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003695 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003696 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003697 Py_DECREF(output);
3698 return 0;
3699 }
3700 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003701 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003702}
3703
3704
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003705int
3706PyUnicode_FSDecoder(PyObject* arg, void* addr)
3707{
Brett Cannona5711202016-09-06 19:36:01 -07003708 int is_buffer = 0;
3709 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003710 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003711 if (arg == NULL) {
3712 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003713 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003714 return 1;
3715 }
Brett Cannona5711202016-09-06 19:36:01 -07003716
3717 is_buffer = PyObject_CheckBuffer(arg);
3718 if (!is_buffer) {
3719 path = PyOS_FSPath(arg);
3720 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003721 return 0;
3722 }
Brett Cannona5711202016-09-06 19:36:01 -07003723 }
3724 else {
3725 path = arg;
3726 Py_INCREF(arg);
3727 }
3728
3729 if (PyUnicode_Check(path)) {
3730 if (PyUnicode_READY(path) == -1) {
3731 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003732 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003733 }
3734 output = path;
3735 }
3736 else if (PyBytes_Check(path) || is_buffer) {
3737 PyObject *path_bytes = NULL;
3738
3739 if (!PyBytes_Check(path) &&
3740 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3741 "path should be string, bytes, or os.PathLike, not %.200s",
3742 Py_TYPE(arg)->tp_name)) {
3743 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003744 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003745 }
3746 path_bytes = PyBytes_FromObject(path);
3747 Py_DECREF(path);
3748 if (!path_bytes) {
3749 return 0;
3750 }
3751 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3752 PyBytes_GET_SIZE(path_bytes));
3753 Py_DECREF(path_bytes);
3754 if (!output) {
3755 return 0;
3756 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003757 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003758 else {
3759 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003760 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003761 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003762 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003763 return 0;
3764 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003765 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003766 Py_DECREF(output);
3767 return 0;
3768 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003769 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003770 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003771 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003772 Py_DECREF(output);
3773 return 0;
3774 }
3775 *(PyObject**)addr = output;
3776 return Py_CLEANUP_SUPPORTED;
3777}
3778
3779
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003780const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003781PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003782{
Christian Heimesf3863112007-11-22 07:46:41 +00003783 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003784
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003785 if (!PyUnicode_Check(unicode)) {
3786 PyErr_BadArgument();
3787 return NULL;
3788 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003789 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003790 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003792 if (PyUnicode_UTF8(unicode) == NULL) {
3793 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003794 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003795 if (bytes == NULL)
3796 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003797 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3798 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003799 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003800 Py_DECREF(bytes);
3801 return NULL;
3802 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003803 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003804 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003805 PyBytes_AS_STRING(bytes),
3806 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003807 Py_DECREF(bytes);
3808 }
3809
3810 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003811 *psize = PyUnicode_UTF8_LENGTH(unicode);
3812 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003813}
3814
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003815const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003817{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003818 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3819}
3820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003821Py_UNICODE *
3822PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3823{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003824 const unsigned char *one_byte;
3825#if SIZEOF_WCHAR_T == 4
3826 const Py_UCS2 *two_bytes;
3827#else
3828 const Py_UCS4 *four_bytes;
3829 const Py_UCS4 *ucs4_end;
3830 Py_ssize_t num_surrogates;
3831#endif
3832 wchar_t *w;
3833 wchar_t *wchar_end;
3834
3835 if (!PyUnicode_Check(unicode)) {
3836 PyErr_BadArgument();
3837 return NULL;
3838 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003839 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003840 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003841 assert(_PyUnicode_KIND(unicode) != 0);
3842 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003843
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003844 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003846 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3847 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003848 num_surrogates = 0;
3849
3850 for (; four_bytes < ucs4_end; ++four_bytes) {
3851 if (*four_bytes > 0xFFFF)
3852 ++num_surrogates;
3853 }
3854
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003855 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3856 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3857 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003858 PyErr_NoMemory();
3859 return NULL;
3860 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003861 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003863 w = _PyUnicode_WSTR(unicode);
3864 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3865 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003866 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3867 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003868 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003869 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003870 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3871 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872 }
3873 else
3874 *w = *four_bytes;
3875
3876 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07003877 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003878 }
3879 }
3880 *w = 0;
3881#else
3882 /* sizeof(wchar_t) == 4 */
3883 Py_FatalError("Impossible unicode object state, wstr and str "
3884 "should share memory already.");
3885 return NULL;
3886#endif
3887 }
3888 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003889 if ((size_t)_PyUnicode_LENGTH(unicode) >
3890 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3891 PyErr_NoMemory();
3892 return NULL;
3893 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003894 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3895 (_PyUnicode_LENGTH(unicode) + 1));
3896 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003897 PyErr_NoMemory();
3898 return NULL;
3899 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003900 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3901 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3902 w = _PyUnicode_WSTR(unicode);
3903 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003904
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003905 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3906 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003907 for (; w < wchar_end; ++one_byte, ++w)
3908 *w = *one_byte;
3909 /* null-terminate the wstr */
3910 *w = 0;
3911 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003912 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003914 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003915 for (; w < wchar_end; ++two_bytes, ++w)
3916 *w = *two_bytes;
3917 /* null-terminate the wstr */
3918 *w = 0;
3919#else
3920 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003921 PyObject_FREE(_PyUnicode_WSTR(unicode));
3922 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923 Py_FatalError("Impossible unicode object state, wstr "
3924 "and str should share memory already.");
3925 return NULL;
3926#endif
3927 }
3928 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07003929 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930 }
3931 }
3932 }
3933 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003934 *size = PyUnicode_WSTR_LENGTH(unicode);
3935 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003936}
3937
Alexander Belopolsky40018472011-02-26 01:02:56 +00003938Py_UNICODE *
3939PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003940{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003941 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003942}
3943
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03003944const Py_UNICODE *
3945_PyUnicode_AsUnicode(PyObject *unicode)
3946{
3947 Py_ssize_t size;
3948 const Py_UNICODE *wstr;
3949
3950 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
3951 if (wstr && wcslen(wstr) != (size_t)size) {
3952 PyErr_SetString(PyExc_ValueError, "embedded null character");
3953 return NULL;
3954 }
3955 return wstr;
3956}
3957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003958
Alexander Belopolsky40018472011-02-26 01:02:56 +00003959Py_ssize_t
3960PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003961{
3962 if (!PyUnicode_Check(unicode)) {
3963 PyErr_BadArgument();
3964 goto onError;
3965 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003966 if (_PyUnicode_WSTR(unicode) == NULL) {
3967 if (PyUnicode_AsUnicode(unicode) == NULL)
3968 goto onError;
3969 }
3970 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003971
Benjamin Peterson29060642009-01-31 22:14:21 +00003972 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003973 return -1;
3974}
3975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003976Py_ssize_t
3977PyUnicode_GetLength(PyObject *unicode)
3978{
Victor Stinner07621332012-06-16 04:53:46 +02003979 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003980 PyErr_BadArgument();
3981 return -1;
3982 }
Victor Stinner07621332012-06-16 04:53:46 +02003983 if (PyUnicode_READY(unicode) == -1)
3984 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003985 return PyUnicode_GET_LENGTH(unicode);
3986}
3987
3988Py_UCS4
3989PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3990{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003991 void *data;
3992 int kind;
3993
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003994 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003995 PyErr_BadArgument();
3996 return (Py_UCS4)-1;
3997 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003998 if (PyUnicode_READY(unicode) == -1) {
3999 return (Py_UCS4)-1;
4000 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004001 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004002 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 return (Py_UCS4)-1;
4004 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004005 data = PyUnicode_DATA(unicode);
4006 kind = PyUnicode_KIND(unicode);
4007 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004008}
4009
4010int
4011PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4012{
4013 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004014 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015 return -1;
4016 }
Victor Stinner488fa492011-12-12 00:01:39 +01004017 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004018 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004019 PyErr_SetString(PyExc_IndexError, "string index out of range");
4020 return -1;
4021 }
Victor Stinner488fa492011-12-12 00:01:39 +01004022 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004023 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004024 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4025 PyErr_SetString(PyExc_ValueError, "character out of range");
4026 return -1;
4027 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004028 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4029 index, ch);
4030 return 0;
4031}
4032
Alexander Belopolsky40018472011-02-26 01:02:56 +00004033const char *
4034PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004035{
Victor Stinner42cb4622010-09-01 19:39:01 +00004036 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004037}
4038
Victor Stinner554f3f02010-06-16 23:33:54 +00004039/* create or adjust a UnicodeDecodeError */
4040static void
4041make_decode_exception(PyObject **exceptionObject,
4042 const char *encoding,
4043 const char *input, Py_ssize_t length,
4044 Py_ssize_t startpos, Py_ssize_t endpos,
4045 const char *reason)
4046{
4047 if (*exceptionObject == NULL) {
4048 *exceptionObject = PyUnicodeDecodeError_Create(
4049 encoding, input, length, startpos, endpos, reason);
4050 }
4051 else {
4052 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4053 goto onError;
4054 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4055 goto onError;
4056 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4057 goto onError;
4058 }
4059 return;
4060
4061onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004062 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004063}
4064
Steve Dowercc16be82016-09-08 10:35:16 -07004065#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004066/* error handling callback helper:
4067 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004068 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004069 and adjust various state variables.
4070 return 0 on success, -1 on error
4071*/
4072
Alexander Belopolsky40018472011-02-26 01:02:56 +00004073static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004074unicode_decode_call_errorhandler_wchar(
4075 const char *errors, PyObject **errorHandler,
4076 const char *encoding, const char *reason,
4077 const char **input, const char **inend, Py_ssize_t *startinpos,
4078 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4079 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004080{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004081 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004082
4083 PyObject *restuple = NULL;
4084 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004085 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004086 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004087 Py_ssize_t requiredsize;
4088 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004089 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004090 wchar_t *repwstr;
4091 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004093 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4094 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004095
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004096 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004097 *errorHandler = PyCodec_LookupError(errors);
4098 if (*errorHandler == NULL)
4099 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004100 }
4101
Victor Stinner554f3f02010-06-16 23:33:54 +00004102 make_decode_exception(exceptionObject,
4103 encoding,
4104 *input, *inend - *input,
4105 *startinpos, *endinpos,
4106 reason);
4107 if (*exceptionObject == NULL)
4108 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004109
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004110 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004111 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004112 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004113 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004114 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004115 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004116 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004117 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004118 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004119
4120 /* Copy back the bytes variables, which might have been modified by the
4121 callback */
4122 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4123 if (!inputobj)
4124 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004125 *input = PyBytes_AS_STRING(inputobj);
4126 insize = PyBytes_GET_SIZE(inputobj);
4127 *inend = *input + insize;
4128 /* we can DECREF safely, as the exception has another reference,
4129 so the object won't go away. */
4130 Py_DECREF(inputobj);
4131
4132 if (newpos<0)
4133 newpos = insize+newpos;
4134 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004135 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004136 goto onError;
4137 }
4138
4139 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4140 if (repwstr == NULL)
4141 goto onError;
4142 /* need more space? (at least enough for what we
4143 have+the replacement+the rest of the string (starting
4144 at the new input position), so we won't have to check space
4145 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004146 requiredsize = *outpos;
4147 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4148 goto overflow;
4149 requiredsize += repwlen;
4150 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4151 goto overflow;
4152 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004153 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004154 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004155 requiredsize = 2*outsize;
4156 if (unicode_resize(output, requiredsize) < 0)
4157 goto onError;
4158 }
4159 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4160 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004161 *endinpos = newpos;
4162 *inptr = *input + newpos;
4163
4164 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004165 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004166 return 0;
4167
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004168 overflow:
4169 PyErr_SetString(PyExc_OverflowError,
4170 "decoded result is too long for a Python string");
4171
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004172 onError:
4173 Py_XDECREF(restuple);
4174 return -1;
4175}
Steve Dowercc16be82016-09-08 10:35:16 -07004176#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004177
4178static int
4179unicode_decode_call_errorhandler_writer(
4180 const char *errors, PyObject **errorHandler,
4181 const char *encoding, const char *reason,
4182 const char **input, const char **inend, Py_ssize_t *startinpos,
4183 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4184 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4185{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004186 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004187
4188 PyObject *restuple = NULL;
4189 PyObject *repunicode = NULL;
4190 Py_ssize_t insize;
4191 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004192 Py_ssize_t replen;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004193 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004194 PyObject *inputobj = NULL;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004195 int need_to_grow = 0;
4196 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004197
4198 if (*errorHandler == NULL) {
4199 *errorHandler = PyCodec_LookupError(errors);
4200 if (*errorHandler == NULL)
4201 goto onError;
4202 }
4203
4204 make_decode_exception(exceptionObject,
4205 encoding,
4206 *input, *inend - *input,
4207 *startinpos, *endinpos,
4208 reason);
4209 if (*exceptionObject == NULL)
4210 goto onError;
4211
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004212 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004213 if (restuple == NULL)
4214 goto onError;
4215 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004216 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004217 goto onError;
4218 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004219 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004220 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004221
4222 /* Copy back the bytes variables, which might have been modified by the
4223 callback */
4224 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4225 if (!inputobj)
4226 goto onError;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004227 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004228 *input = PyBytes_AS_STRING(inputobj);
4229 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004230 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004231 /* we can DECREF safely, as the exception has another reference,
4232 so the object won't go away. */
4233 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004234
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004235 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004236 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004237 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004238 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004239 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004240 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004241
Victor Stinner170ca6f2013-04-18 00:25:28 +02004242 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004243 if (replen > 1) {
4244 writer->min_length += replen - 1;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004245 need_to_grow = 1;
4246 }
4247 new_inptr = *input + newpos;
4248 if (*inend - new_inptr > remain) {
4249 /* We don't know the decoding algorithm here so we make the worst
4250 assumption that one byte decodes to one unicode character.
4251 If unfortunately one byte could decode to more unicode characters,
4252 the decoder may write out-of-bound then. Is it possible for the
4253 algorithms using this function? */
4254 writer->min_length += *inend - new_inptr - remain;
4255 need_to_grow = 1;
4256 }
4257 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004258 writer->overallocate = 1;
Miss Islington (bot)09819ef2018-02-12 23:15:57 -08004259 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004260 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4261 goto onError;
4262 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004263 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004264 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004265
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266 *endinpos = newpos;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004267 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004268
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004269 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004270 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004271 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004272
Benjamin Peterson29060642009-01-31 22:14:21 +00004273 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004274 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004275 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004276}
4277
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004278/* --- UTF-7 Codec -------------------------------------------------------- */
4279
Antoine Pitrou244651a2009-05-04 18:56:13 +00004280/* See RFC2152 for details. We encode conservatively and decode liberally. */
4281
4282/* Three simple macros defining base-64. */
4283
4284/* Is c a base-64 character? */
4285
4286#define IS_BASE64(c) \
4287 (((c) >= 'A' && (c) <= 'Z') || \
4288 ((c) >= 'a' && (c) <= 'z') || \
4289 ((c) >= '0' && (c) <= '9') || \
4290 (c) == '+' || (c) == '/')
4291
4292/* given that c is a base-64 character, what is its base-64 value? */
4293
4294#define FROM_BASE64(c) \
4295 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4296 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4297 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4298 (c) == '+' ? 62 : 63)
4299
4300/* What is the base-64 character of the bottom 6 bits of n? */
4301
4302#define TO_BASE64(n) \
4303 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4304
4305/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4306 * decoded as itself. We are permissive on decoding; the only ASCII
4307 * byte not decoding to itself is the + which begins a base64
4308 * string. */
4309
4310#define DECODE_DIRECT(c) \
4311 ((c) <= 127 && (c) != '+')
4312
4313/* The UTF-7 encoder treats ASCII characters differently according to
4314 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4315 * the above). See RFC2152. This array identifies these different
4316 * sets:
4317 * 0 : "Set D"
4318 * alphanumeric and '(),-./:?
4319 * 1 : "Set O"
4320 * !"#$%&*;<=>@[]^_`{|}
4321 * 2 : "whitespace"
4322 * ht nl cr sp
4323 * 3 : special (must be base64 encoded)
4324 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4325 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326
Tim Petersced69f82003-09-16 20:30:58 +00004327static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004328char utf7_category[128] = {
4329/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4330 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4331/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4332 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4333/* sp ! " # $ % & ' ( ) * + , - . / */
4334 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4335/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4336 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4337/* @ A B C D E F G H I J K L M N O */
4338 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4339/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4340 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4341/* ` a b c d e f g h i j k l m n o */
4342 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4343/* p q r s t u v w x y z { | } ~ del */
4344 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345};
4346
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347/* ENCODE_DIRECT: this character should be encoded as itself. The
4348 * answer depends on whether we are encoding set O as itself, and also
4349 * on whether we are encoding whitespace as itself. RFC2152 makes it
4350 * clear that the answers to these questions vary between
4351 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004352
Antoine Pitrou244651a2009-05-04 18:56:13 +00004353#define ENCODE_DIRECT(c, directO, directWS) \
4354 ((c) < 128 && (c) > 0 && \
4355 ((utf7_category[(c)] == 0) || \
4356 (directWS && (utf7_category[(c)] == 2)) || \
4357 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004358
Alexander Belopolsky40018472011-02-26 01:02:56 +00004359PyObject *
4360PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004361 Py_ssize_t size,
4362 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004363{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004364 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4365}
4366
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367/* The decoder. The only state we preserve is our read position,
4368 * i.e. how many characters we have consumed. So if we end in the
4369 * middle of a shift sequence we have to back off the read position
4370 * and the output to the beginning of the sequence, otherwise we lose
4371 * all the shift state (seen bits, number of bits seen, high
4372 * surrogate). */
4373
Alexander Belopolsky40018472011-02-26 01:02:56 +00004374PyObject *
4375PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004376 Py_ssize_t size,
4377 const char *errors,
4378 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004379{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004380 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004381 Py_ssize_t startinpos;
4382 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004384 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004385 const char *errmsg = "";
4386 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004387 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388 unsigned int base64bits = 0;
4389 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004390 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004391 PyObject *errorHandler = NULL;
4392 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004393
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004394 if (size == 0) {
4395 if (consumed)
4396 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004397 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004398 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004399
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004400 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004401 _PyUnicodeWriter_Init(&writer);
4402 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004403
4404 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004405 e = s + size;
4406
4407 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004408 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004409 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004410 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 if (inShift) { /* in a base-64 section */
4413 if (IS_BASE64(ch)) { /* consume a base-64 character */
4414 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4415 base64bits += 6;
4416 s++;
4417 if (base64bits >= 16) {
4418 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004419 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 base64bits -= 16;
4421 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004422 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 if (surrogate) {
4424 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004425 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4426 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004427 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004428 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004429 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004430 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 }
4432 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004433 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004434 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004435 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004436 }
4437 }
Victor Stinner551ac952011-11-29 22:58:13 +01004438 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004439 /* first surrogate */
4440 surrogate = outCh;
4441 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004442 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004443 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004444 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445 }
4446 }
4447 }
4448 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004449 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004450 if (base64bits > 0) { /* left-over bits */
4451 if (base64bits >= 6) {
4452 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004453 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004454 errmsg = "partial character in shift sequence";
4455 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004456 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 else {
4458 /* Some bits remain; they should be zero */
4459 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004460 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 errmsg = "non-zero padding bits in shift sequence";
4462 goto utf7Error;
4463 }
4464 }
4465 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004466 if (surrogate && DECODE_DIRECT(ch)) {
4467 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4468 goto onError;
4469 }
4470 surrogate = 0;
4471 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004472 /* '-' is absorbed; other terminating
4473 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004474 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004475 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004476 }
4477 }
4478 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004479 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004480 s++; /* consume '+' */
4481 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004482 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004483 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004484 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004485 }
4486 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004487 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004488 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004489 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004491 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004492 }
4493 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004494 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004495 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004496 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004497 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004498 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004499 else {
4500 startinpos = s-starts;
4501 s++;
4502 errmsg = "unexpected special character";
4503 goto utf7Error;
4504 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004507 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004508 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004509 errors, &errorHandler,
4510 "utf7", errmsg,
4511 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004512 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004513 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004514 }
4515
Antoine Pitrou244651a2009-05-04 18:56:13 +00004516 /* end of string */
4517
4518 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4519 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004520 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004521 if (surrogate ||
4522 (base64bits >= 6) ||
4523 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004524 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004525 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 errors, &errorHandler,
4527 "utf7", "unterminated shift sequence",
4528 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004529 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004530 goto onError;
4531 if (s < e)
4532 goto restart;
4533 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535
4536 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004537 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004538 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004539 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004540 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004541 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004542 writer.kind, writer.data, shiftOutStart);
4543 Py_XDECREF(errorHandler);
4544 Py_XDECREF(exc);
4545 _PyUnicodeWriter_Dealloc(&writer);
4546 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004547 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004548 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 }
4550 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004551 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004552 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004553 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004555 Py_XDECREF(errorHandler);
4556 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004557 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004558
Benjamin Peterson29060642009-01-31 22:14:21 +00004559 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004560 Py_XDECREF(errorHandler);
4561 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004562 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004563 return NULL;
4564}
4565
4566
Alexander Belopolsky40018472011-02-26 01:02:56 +00004567PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004568_PyUnicode_EncodeUTF7(PyObject *str,
4569 int base64SetO,
4570 int base64WhiteSpace,
4571 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004572{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004573 int kind;
4574 void *data;
4575 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004576 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004577 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004578 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004579 unsigned int base64bits = 0;
4580 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004581 char * out;
4582 char * start;
4583
Benjamin Petersonbac79492012-01-14 13:34:47 -05004584 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004585 return NULL;
4586 kind = PyUnicode_KIND(str);
4587 data = PyUnicode_DATA(str);
4588 len = PyUnicode_GET_LENGTH(str);
4589
4590 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004591 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004592
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004593 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004594 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004595 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004596 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004597 if (v == NULL)
4598 return NULL;
4599
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004600 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004601 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004602 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004603
Antoine Pitrou244651a2009-05-04 18:56:13 +00004604 if (inShift) {
4605 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4606 /* shifting out */
4607 if (base64bits) { /* output remaining bits */
4608 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4609 base64buffer = 0;
4610 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004611 }
4612 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004613 /* Characters not in the BASE64 set implicitly unshift the sequence
4614 so no '-' is required, except if the character is itself a '-' */
4615 if (IS_BASE64(ch) || ch == '-') {
4616 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004617 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004618 *out++ = (char) ch;
4619 }
4620 else {
4621 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004622 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004623 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004624 else { /* not in a shift sequence */
4625 if (ch == '+') {
4626 *out++ = '+';
4627 *out++ = '-';
4628 }
4629 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4630 *out++ = (char) ch;
4631 }
4632 else {
4633 *out++ = '+';
4634 inShift = 1;
4635 goto encode_char;
4636 }
4637 }
4638 continue;
4639encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004640 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004641 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004642
Antoine Pitrou244651a2009-05-04 18:56:13 +00004643 /* code first surrogate */
4644 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004645 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004646 while (base64bits >= 6) {
4647 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4648 base64bits -= 6;
4649 }
4650 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004651 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004652 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004653 base64bits += 16;
4654 base64buffer = (base64buffer << 16) | ch;
4655 while (base64bits >= 6) {
4656 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4657 base64bits -= 6;
4658 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004659 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004660 if (base64bits)
4661 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4662 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004663 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004664 if (_PyBytes_Resize(&v, out - start) < 0)
4665 return NULL;
4666 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004667}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004668PyObject *
4669PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4670 Py_ssize_t size,
4671 int base64SetO,
4672 int base64WhiteSpace,
4673 const char *errors)
4674{
4675 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004676 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004677 if (tmp == NULL)
4678 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004679 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004680 base64WhiteSpace, errors);
4681 Py_DECREF(tmp);
4682 return result;
4683}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004684
Antoine Pitrou244651a2009-05-04 18:56:13 +00004685#undef IS_BASE64
4686#undef FROM_BASE64
4687#undef TO_BASE64
4688#undef DECODE_DIRECT
4689#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004690
Guido van Rossumd57fd912000-03-10 22:53:23 +00004691/* --- UTF-8 Codec -------------------------------------------------------- */
4692
Alexander Belopolsky40018472011-02-26 01:02:56 +00004693PyObject *
4694PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004695 Py_ssize_t size,
4696 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004697{
Walter Dörwald69652032004-09-07 20:24:22 +00004698 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4699}
4700
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004701#include "stringlib/asciilib.h"
4702#include "stringlib/codecs.h"
4703#include "stringlib/undef.h"
4704
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004705#include "stringlib/ucs1lib.h"
4706#include "stringlib/codecs.h"
4707#include "stringlib/undef.h"
4708
4709#include "stringlib/ucs2lib.h"
4710#include "stringlib/codecs.h"
4711#include "stringlib/undef.h"
4712
4713#include "stringlib/ucs4lib.h"
4714#include "stringlib/codecs.h"
4715#include "stringlib/undef.h"
4716
Antoine Pitrouab868312009-01-10 15:40:25 +00004717/* Mask to quickly check whether a C 'long' contains a
4718 non-ASCII, UTF8-encoded char. */
4719#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004720# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004721#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004722# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004723#else
4724# error C 'long' size should be either 4 or 8!
4725#endif
4726
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727static Py_ssize_t
4728ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004729{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004731 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004732
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004733 /*
4734 * Issue #17237: m68k is a bit different from most architectures in
4735 * that objects do not use "natural alignment" - for example, int and
4736 * long are only aligned at 2-byte boundaries. Therefore the assert()
4737 * won't work; also, tests have shown that skipping the "optimised
4738 * version" will even speed up m68k.
4739 */
4740#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004741#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004742 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4743 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004744 /* Fast path, see in STRINGLIB(utf8_decode) for
4745 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004746 /* Help allocation */
4747 const char *_p = p;
4748 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004749 while (_p < aligned_end) {
4750 unsigned long value = *(const unsigned long *) _p;
4751 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004752 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 *((unsigned long *)q) = value;
4754 _p += SIZEOF_LONG;
4755 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004756 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004757 p = _p;
4758 while (p < end) {
4759 if ((unsigned char)*p & 0x80)
4760 break;
4761 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004762 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004764 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004765#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004766#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767 while (p < end) {
4768 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4769 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004770 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004771 /* Help allocation */
4772 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004773 while (_p < aligned_end) {
4774 unsigned long value = *(unsigned long *) _p;
4775 if (value & ASCII_CHAR_MASK)
4776 break;
4777 _p += SIZEOF_LONG;
4778 }
4779 p = _p;
4780 if (_p == end)
4781 break;
4782 }
4783 if ((unsigned char)*p & 0x80)
4784 break;
4785 ++p;
4786 }
4787 memcpy(dest, start, p - start);
4788 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004789}
Antoine Pitrouab868312009-01-10 15:40:25 +00004790
Victor Stinner785938e2011-12-11 20:09:03 +01004791PyObject *
4792PyUnicode_DecodeUTF8Stateful(const char *s,
4793 Py_ssize_t size,
4794 const char *errors,
4795 Py_ssize_t *consumed)
4796{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004797 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004798 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800
4801 Py_ssize_t startinpos;
4802 Py_ssize_t endinpos;
4803 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004804 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004805 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004806 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004807
4808 if (size == 0) {
4809 if (consumed)
4810 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004811 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004812 }
4813
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004814 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4815 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004816 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004817 *consumed = 1;
4818 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004819 }
4820
Victor Stinner8f674cc2013-04-17 23:02:17 +02004821 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004822 writer.min_length = size;
4823 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004824 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004825
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004826 writer.pos = ascii_decode(s, end, writer.data);
4827 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004828 while (s < end) {
4829 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004830 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004831
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004832 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004833 if (PyUnicode_IS_ASCII(writer.buffer))
4834 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004836 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004838 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 } else {
4840 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004841 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004842 }
4843
4844 switch (ch) {
4845 case 0:
4846 if (s == end || consumed)
4847 goto End;
4848 errmsg = "unexpected end of data";
4849 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004850 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004851 break;
4852 case 1:
4853 errmsg = "invalid start byte";
4854 startinpos = s - starts;
4855 endinpos = startinpos + 1;
4856 break;
4857 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004858 case 3:
4859 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004860 errmsg = "invalid continuation byte";
4861 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004862 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004863 break;
4864 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004865 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004866 goto onError;
4867 continue;
4868 }
4869
Victor Stinner1d65d912015-10-05 13:43:50 +02004870 if (error_handler == _Py_ERROR_UNKNOWN)
4871 error_handler = get_error_handler(errors);
4872
4873 switch (error_handler) {
4874 case _Py_ERROR_IGNORE:
4875 s += (endinpos - startinpos);
4876 break;
4877
4878 case _Py_ERROR_REPLACE:
4879 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4880 goto onError;
4881 s += (endinpos - startinpos);
4882 break;
4883
4884 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004885 {
4886 Py_ssize_t i;
4887
Victor Stinner1d65d912015-10-05 13:43:50 +02004888 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4889 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004890 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004891 ch = (Py_UCS4)(unsigned char)(starts[i]);
4892 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4893 ch + 0xdc00);
4894 writer.pos++;
4895 }
4896 s += (endinpos - startinpos);
4897 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004898 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004899
4900 default:
4901 if (unicode_decode_call_errorhandler_writer(
4902 errors, &error_handler_obj,
4903 "utf-8", errmsg,
4904 &starts, &end, &startinpos, &endinpos, &exc, &s,
4905 &writer))
4906 goto onError;
4907 }
Victor Stinner785938e2011-12-11 20:09:03 +01004908 }
4909
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911 if (consumed)
4912 *consumed = s - starts;
4913
Victor Stinner1d65d912015-10-05 13:43:50 +02004914 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004915 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004916 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004917
4918onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004919 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004920 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004921 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004922 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004923}
4924
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004925
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004926/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4927 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004928
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004929 On success, write a pointer to a newly allocated wide character string into
4930 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4931 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004932
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004933 On memory allocation failure, return -1.
4934
4935 On decoding error (if surrogateescape is zero), return -2. If wlen is
4936 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4937 is not NULL, write the decoding error message into *reason. */
4938int
4939_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
4940 const char **reason, int surrogateescape)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004941{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004942 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004943 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004944 wchar_t *unicode;
4945 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004946
4947 /* Note: size will always be longer than the resulting Unicode
4948 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004949 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004950 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004951 }
4952
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004953 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004954 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004955 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004956 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004957
4958 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004959 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004961 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004963#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004964 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004965#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004966 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004967#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004968 if (ch > 0xFF) {
4969#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07004970 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004971#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02004972 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004973 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4975 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4976#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004977 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004978 else {
4979 if (!ch && s == e)
4980 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004981 if (!surrogateescape) {
4982 PyMem_RawFree(unicode );
4983 if (reason != NULL) {
4984 switch (ch) {
4985 case 0:
4986 *reason = "unexpected end of data";
4987 break;
4988 case 1:
4989 *reason = "invalid start byte";
4990 break;
4991 /* 2, 3, 4 */
4992 default:
4993 *reason = "invalid continuation byte";
4994 break;
4995 }
4996 }
4997 if (wlen != NULL) {
4998 *wlen = s - orig_s;
4999 }
5000 return -2;
5001 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 /* surrogateescape */
5003 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5004 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005005 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005006 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005007 if (wlen) {
5008 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005009 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005010 *wstr = unicode;
5011 return 0;
5012}
5013
5014wchar_t*
5015_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen)
5016{
5017 wchar_t *wstr;
5018 int res = _Py_DecodeUTF8Ex(arg, arglen, &wstr, NULL, NULL, 1);
5019 if (res != 0) {
5020 return NULL;
5021 }
5022 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005023}
5024
Antoine Pitrouab868312009-01-10 15:40:25 +00005025
Victor Stinnere47e6982017-12-21 15:45:16 +01005026/* UTF-8 encoder using the surrogateescape error handler .
5027
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005028 On success, return 0 and write the newly allocated character string (use
5029 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005030
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005031 On encoding failure, return -2 and write the position of the invalid
5032 surrogate character into *error_pos (if error_pos is set) and the decoding
5033 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005034
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005035 On memory allocation failure, return -1. */
5036int
5037_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
5038 const char **reason, int raw_malloc, int surrogateescape)
Victor Stinnere47e6982017-12-21 15:45:16 +01005039{
5040 const Py_ssize_t max_char_size = 4;
5041 Py_ssize_t len = wcslen(text);
5042
5043 assert(len >= 0);
5044
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005045 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5046 return -1;
5047 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005048 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005049 if (raw_malloc) {
5050 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005051 }
5052 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005053 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005054 }
5055 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005056 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005057 }
5058
5059 char *p = bytes;
5060 Py_ssize_t i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005061 for (i = 0; i < len; i++) {
5062 Py_UCS4 ch = text[i];
Victor Stinnere47e6982017-12-21 15:45:16 +01005063
5064 if (ch < 0x80) {
5065 /* Encode ASCII */
5066 *p++ = (char) ch;
5067
5068 }
5069 else if (ch < 0x0800) {
5070 /* Encode Latin-1 */
5071 *p++ = (char)(0xc0 | (ch >> 6));
5072 *p++ = (char)(0x80 | (ch & 0x3f));
5073 }
5074 else if (Py_UNICODE_IS_SURROGATE(ch)) {
5075 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005076 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005077 if (error_pos != NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005078 *error_pos = (size_t)i;
Victor Stinnere47e6982017-12-21 15:45:16 +01005079 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005080 if (reason != NULL) {
5081 *reason = "encoding error";
5082 }
5083 if (raw_malloc) {
5084 PyMem_RawFree(bytes);
5085 }
5086 else {
5087 PyMem_Free(bytes);
5088 }
5089 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005090 }
5091 *p++ = (char)(ch & 0xff);
5092 }
5093 else if (ch < 0x10000) {
5094 *p++ = (char)(0xe0 | (ch >> 12));
5095 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5096 *p++ = (char)(0x80 | (ch & 0x3f));
5097 }
5098 else { /* ch >= 0x10000 */
5099 assert(ch <= MAX_UNICODE);
5100 /* Encode UCS4 Unicode ordinals */
5101 *p++ = (char)(0xf0 | (ch >> 18));
5102 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5103 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5104 *p++ = (char)(0x80 | (ch & 0x3f));
5105 }
5106 }
5107 *p++ = '\0';
5108
5109 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005110 char *bytes2;
5111 if (raw_malloc) {
5112 bytes2 = PyMem_RawRealloc(bytes, final_size);
5113 }
5114 else {
5115 bytes2 = PyMem_Realloc(bytes, final_size);
5116 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005117 if (bytes2 == NULL) {
5118 if (error_pos != NULL) {
5119 *error_pos = (size_t)-1;
5120 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005121 if (raw_malloc) {
5122 PyMem_RawFree(bytes);
5123 }
5124 else {
5125 PyMem_Free(bytes);
5126 }
5127 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005128 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005129 *str = bytes2;
5130 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005131}
5132
5133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005134/* Primary internal function which creates utf8 encoded bytes objects.
5135
5136 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005137 and allocate exactly as much space needed at the end. Else allocate the
5138 maximum possible needed (4 result bytes per Unicode character), and return
5139 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005140*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005141PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005142_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005143{
Victor Stinner6099a032011-12-18 14:22:26 +01005144 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005145 void *data;
5146 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005148 if (!PyUnicode_Check(unicode)) {
5149 PyErr_BadArgument();
5150 return NULL;
5151 }
5152
5153 if (PyUnicode_READY(unicode) == -1)
5154 return NULL;
5155
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005156 if (PyUnicode_UTF8(unicode))
5157 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5158 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005159
5160 kind = PyUnicode_KIND(unicode);
5161 data = PyUnicode_DATA(unicode);
5162 size = PyUnicode_GET_LENGTH(unicode);
5163
Benjamin Petersonead6b532011-12-20 17:23:42 -06005164 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005165 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005166 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005167 case PyUnicode_1BYTE_KIND:
5168 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5169 assert(!PyUnicode_IS_ASCII(unicode));
5170 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5171 case PyUnicode_2BYTE_KIND:
5172 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5173 case PyUnicode_4BYTE_KIND:
5174 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005175 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005176}
5177
Alexander Belopolsky40018472011-02-26 01:02:56 +00005178PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005179PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5180 Py_ssize_t size,
5181 const char *errors)
5182{
5183 PyObject *v, *unicode;
5184
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005185 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005186 if (unicode == NULL)
5187 return NULL;
5188 v = _PyUnicode_AsUTF8String(unicode, errors);
5189 Py_DECREF(unicode);
5190 return v;
5191}
5192
5193PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005194PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005195{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005196 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005197}
5198
Walter Dörwald41980ca2007-08-16 21:55:45 +00005199/* --- UTF-32 Codec ------------------------------------------------------- */
5200
5201PyObject *
5202PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005203 Py_ssize_t size,
5204 const char *errors,
5205 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005206{
5207 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5208}
5209
5210PyObject *
5211PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005212 Py_ssize_t size,
5213 const char *errors,
5214 int *byteorder,
5215 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005216{
5217 const char *starts = s;
5218 Py_ssize_t startinpos;
5219 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005220 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005221 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005222 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005223 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005224 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005225 PyObject *errorHandler = NULL;
5226 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005227
Walter Dörwald41980ca2007-08-16 21:55:45 +00005228 q = (unsigned char *)s;
5229 e = q + size;
5230
5231 if (byteorder)
5232 bo = *byteorder;
5233
5234 /* Check for BOM marks (U+FEFF) in the input and adjust current
5235 byte order setting accordingly. In native mode, the leading BOM
5236 mark is skipped, in all other modes, it is copied to the output
5237 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005238 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005239 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005240 if (bom == 0x0000FEFF) {
5241 bo = -1;
5242 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005244 else if (bom == 0xFFFE0000) {
5245 bo = 1;
5246 q += 4;
5247 }
5248 if (byteorder)
5249 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005250 }
5251
Victor Stinnere64322e2012-10-30 23:12:47 +01005252 if (q == e) {
5253 if (consumed)
5254 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005255 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005256 }
5257
Victor Stinnere64322e2012-10-30 23:12:47 +01005258#ifdef WORDS_BIGENDIAN
5259 le = bo < 0;
5260#else
5261 le = bo <= 0;
5262#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005263 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005264
Victor Stinner8f674cc2013-04-17 23:02:17 +02005265 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005266 writer.min_length = (e - q + 3) / 4;
5267 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005268 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005269
Victor Stinnere64322e2012-10-30 23:12:47 +01005270 while (1) {
5271 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005272 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005273
Victor Stinnere64322e2012-10-30 23:12:47 +01005274 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005275 enum PyUnicode_Kind kind = writer.kind;
5276 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005277 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005278 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005279 if (le) {
5280 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005281 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005282 if (ch > maxch)
5283 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005284 if (kind != PyUnicode_1BYTE_KIND &&
5285 Py_UNICODE_IS_SURROGATE(ch))
5286 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005287 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005288 q += 4;
5289 } while (q <= last);
5290 }
5291 else {
5292 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005293 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005294 if (ch > maxch)
5295 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005296 if (kind != PyUnicode_1BYTE_KIND &&
5297 Py_UNICODE_IS_SURROGATE(ch))
5298 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005299 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005300 q += 4;
5301 } while (q <= last);
5302 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005303 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005304 }
5305
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005306 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005307 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005308 startinpos = ((const char *)q) - starts;
5309 endinpos = startinpos + 4;
5310 }
5311 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005312 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005313 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005314 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005315 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005316 startinpos = ((const char *)q) - starts;
5317 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005318 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005319 else {
5320 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005321 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005322 goto onError;
5323 q += 4;
5324 continue;
5325 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005326 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005327 startinpos = ((const char *)q) - starts;
5328 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005330
5331 /* The remaining input chars are ignored if the callback
5332 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005333 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005335 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005337 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005339 }
5340
Walter Dörwald41980ca2007-08-16 21:55:45 +00005341 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005342 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005343
Walter Dörwald41980ca2007-08-16 21:55:45 +00005344 Py_XDECREF(errorHandler);
5345 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005346 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005347
Benjamin Peterson29060642009-01-31 22:14:21 +00005348 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005349 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005350 Py_XDECREF(errorHandler);
5351 Py_XDECREF(exc);
5352 return NULL;
5353}
5354
5355PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005356_PyUnicode_EncodeUTF32(PyObject *str,
5357 const char *errors,
5358 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005359{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005360 enum PyUnicode_Kind kind;
5361 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005362 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005363 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005364 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005365#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005366 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005367#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005368 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005369#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005370 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005371 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005372 PyObject *errorHandler = NULL;
5373 PyObject *exc = NULL;
5374 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005375
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005376 if (!PyUnicode_Check(str)) {
5377 PyErr_BadArgument();
5378 return NULL;
5379 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005380 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005381 return NULL;
5382 kind = PyUnicode_KIND(str);
5383 data = PyUnicode_DATA(str);
5384 len = PyUnicode_GET_LENGTH(str);
5385
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005386 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005387 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005388 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005389 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005390 if (v == NULL)
5391 return NULL;
5392
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005393 /* output buffer is 4-bytes aligned */
5394 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005395 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005396 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005397 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005398 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005399 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005400
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005401 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005402 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005403 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005404 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005405 else
5406 encoding = "utf-32";
5407
5408 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005409 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5410 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005411 }
5412
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005413 pos = 0;
5414 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005415 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005416
5417 if (kind == PyUnicode_2BYTE_KIND) {
5418 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5419 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005420 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005421 else {
5422 assert(kind == PyUnicode_4BYTE_KIND);
5423 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5424 &out, native_ordering);
5425 }
5426 if (pos == len)
5427 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005428
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005429 rep = unicode_encode_call_errorhandler(
5430 errors, &errorHandler,
5431 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005432 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005433 if (!rep)
5434 goto error;
5435
5436 if (PyBytes_Check(rep)) {
5437 repsize = PyBytes_GET_SIZE(rep);
5438 if (repsize & 3) {
5439 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005440 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005441 "surrogates not allowed");
5442 goto error;
5443 }
5444 moreunits = repsize / 4;
5445 }
5446 else {
5447 assert(PyUnicode_Check(rep));
5448 if (PyUnicode_READY(rep) < 0)
5449 goto error;
5450 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5451 if (!PyUnicode_IS_ASCII(rep)) {
5452 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005453 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005454 "surrogates not allowed");
5455 goto error;
5456 }
5457 }
5458
5459 /* four bytes are reserved for each surrogate */
5460 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005461 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005462 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005463 /* integer overflow */
5464 PyErr_NoMemory();
5465 goto error;
5466 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005467 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005468 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005469 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005470 }
5471
5472 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005473 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005474 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005475 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005476 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005477 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5478 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005479 }
5480
5481 Py_CLEAR(rep);
5482 }
5483
5484 /* Cut back to size actually needed. This is necessary for, for example,
5485 encoding of a string containing isolated surrogates and the 'ignore'
5486 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005487 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005488 if (nsize != PyBytes_GET_SIZE(v))
5489 _PyBytes_Resize(&v, nsize);
5490 Py_XDECREF(errorHandler);
5491 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005492 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005493 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005494 error:
5495 Py_XDECREF(rep);
5496 Py_XDECREF(errorHandler);
5497 Py_XDECREF(exc);
5498 Py_XDECREF(v);
5499 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005500}
5501
Alexander Belopolsky40018472011-02-26 01:02:56 +00005502PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005503PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5504 Py_ssize_t size,
5505 const char *errors,
5506 int byteorder)
5507{
5508 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005509 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005510 if (tmp == NULL)
5511 return NULL;
5512 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5513 Py_DECREF(tmp);
5514 return result;
5515}
5516
5517PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005518PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005519{
Victor Stinnerb960b342011-11-20 19:12:52 +01005520 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005521}
5522
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523/* --- UTF-16 Codec ------------------------------------------------------- */
5524
Tim Peters772747b2001-08-09 22:21:55 +00005525PyObject *
5526PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005527 Py_ssize_t size,
5528 const char *errors,
5529 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005530{
Walter Dörwald69652032004-09-07 20:24:22 +00005531 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5532}
5533
5534PyObject *
5535PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005536 Py_ssize_t size,
5537 const char *errors,
5538 int *byteorder,
5539 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005540{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005541 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005542 Py_ssize_t startinpos;
5543 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005544 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005545 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005546 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005547 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005548 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005549 PyObject *errorHandler = NULL;
5550 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005551 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005552
Tim Peters772747b2001-08-09 22:21:55 +00005553 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005554 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005555
5556 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005557 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005558
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005559 /* Check for BOM marks (U+FEFF) in the input and adjust current
5560 byte order setting accordingly. In native mode, the leading BOM
5561 mark is skipped, in all other modes, it is copied to the output
5562 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005563 if (bo == 0 && size >= 2) {
5564 const Py_UCS4 bom = (q[1] << 8) | q[0];
5565 if (bom == 0xFEFF) {
5566 q += 2;
5567 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005568 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005569 else if (bom == 0xFFFE) {
5570 q += 2;
5571 bo = 1;
5572 }
5573 if (byteorder)
5574 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005575 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005576
Antoine Pitrou63065d72012-05-15 23:48:04 +02005577 if (q == e) {
5578 if (consumed)
5579 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005580 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005581 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005582
Christian Heimes743e0cd2012-10-17 23:52:17 +02005583#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005584 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005585 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005586#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005587 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005588 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005589#endif
Tim Peters772747b2001-08-09 22:21:55 +00005590
Antoine Pitrou63065d72012-05-15 23:48:04 +02005591 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang86fdad02018-01-31 20:48:05 +08005592 character count normally. Error handler will take care of
5593 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005594 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005595 writer.min_length = (e - q + 1) / 2;
5596 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005597 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005598
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599 while (1) {
5600 Py_UCS4 ch = 0;
5601 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005602 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005603 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005604 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005605 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005606 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005607 native_ordering);
5608 else
5609 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005610 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005611 native_ordering);
5612 } else if (kind == PyUnicode_2BYTE_KIND) {
5613 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005614 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005615 native_ordering);
5616 } else {
5617 assert(kind == PyUnicode_4BYTE_KIND);
5618 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005619 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005620 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005621 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005622 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005623
Antoine Pitrou63065d72012-05-15 23:48:04 +02005624 switch (ch)
5625 {
5626 case 0:
5627 /* remaining byte at the end? (size should be even) */
5628 if (q == e || consumed)
5629 goto End;
5630 errmsg = "truncated data";
5631 startinpos = ((const char *)q) - starts;
5632 endinpos = ((const char *)e) - starts;
5633 break;
5634 /* The remaining input chars are ignored if the callback
5635 chooses to skip the input */
5636 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005637 q -= 2;
5638 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005639 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005640 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005641 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005642 endinpos = ((const char *)e) - starts;
5643 break;
5644 case 2:
5645 errmsg = "illegal encoding";
5646 startinpos = ((const char *)q) - 2 - starts;
5647 endinpos = startinpos + 2;
5648 break;
5649 case 3:
5650 errmsg = "illegal UTF-16 surrogate";
5651 startinpos = ((const char *)q) - 4 - starts;
5652 endinpos = startinpos + 2;
5653 break;
5654 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005655 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005656 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005657 continue;
5658 }
5659
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005660 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005661 errors,
5662 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005663 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005664 &starts,
5665 (const char **)&e,
5666 &startinpos,
5667 &endinpos,
5668 &exc,
5669 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005670 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005671 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005672 }
5673
Antoine Pitrou63065d72012-05-15 23:48:04 +02005674End:
Walter Dörwald69652032004-09-07 20:24:22 +00005675 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005676 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005677
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005678 Py_XDECREF(errorHandler);
5679 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005680 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005681
Benjamin Peterson29060642009-01-31 22:14:21 +00005682 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005683 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005684 Py_XDECREF(errorHandler);
5685 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686 return NULL;
5687}
5688
Tim Peters772747b2001-08-09 22:21:55 +00005689PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005690_PyUnicode_EncodeUTF16(PyObject *str,
5691 const char *errors,
5692 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005694 enum PyUnicode_Kind kind;
5695 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005696 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005697 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005698 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005699 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005700#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005701 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005702#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005703 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005704#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005705 const char *encoding;
5706 Py_ssize_t nsize, pos;
5707 PyObject *errorHandler = NULL;
5708 PyObject *exc = NULL;
5709 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005710
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005711 if (!PyUnicode_Check(str)) {
5712 PyErr_BadArgument();
5713 return NULL;
5714 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005715 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005716 return NULL;
5717 kind = PyUnicode_KIND(str);
5718 data = PyUnicode_DATA(str);
5719 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005720
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005721 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005722 if (kind == PyUnicode_4BYTE_KIND) {
5723 const Py_UCS4 *in = (const Py_UCS4 *)data;
5724 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005725 while (in < end) {
5726 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005727 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005728 }
5729 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005730 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005731 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005732 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005733 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005734 nsize = len + pairs + (byteorder == 0);
5735 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005736 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005738 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005740 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005741 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005742 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005743 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005744 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005745 }
5746 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005747 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005748 }
Tim Peters772747b2001-08-09 22:21:55 +00005749
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005750 if (kind == PyUnicode_1BYTE_KIND) {
5751 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5752 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005753 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005754
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005755 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005756 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005757 }
5758 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005759 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005760 }
5761 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005762 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005763 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005764
5765 pos = 0;
5766 while (pos < len) {
5767 Py_ssize_t repsize, moreunits;
5768
5769 if (kind == PyUnicode_2BYTE_KIND) {
5770 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5771 &out, native_ordering);
5772 }
5773 else {
5774 assert(kind == PyUnicode_4BYTE_KIND);
5775 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5776 &out, native_ordering);
5777 }
5778 if (pos == len)
5779 break;
5780
5781 rep = unicode_encode_call_errorhandler(
5782 errors, &errorHandler,
5783 encoding, "surrogates not allowed",
5784 str, &exc, pos, pos + 1, &pos);
5785 if (!rep)
5786 goto error;
5787
5788 if (PyBytes_Check(rep)) {
5789 repsize = PyBytes_GET_SIZE(rep);
5790 if (repsize & 1) {
5791 raise_encode_exception(&exc, encoding,
5792 str, pos - 1, pos,
5793 "surrogates not allowed");
5794 goto error;
5795 }
5796 moreunits = repsize / 2;
5797 }
5798 else {
5799 assert(PyUnicode_Check(rep));
5800 if (PyUnicode_READY(rep) < 0)
5801 goto error;
5802 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5803 if (!PyUnicode_IS_ASCII(rep)) {
5804 raise_encode_exception(&exc, encoding,
5805 str, pos - 1, pos,
5806 "surrogates not allowed");
5807 goto error;
5808 }
5809 }
5810
5811 /* two bytes are reserved for each surrogate */
5812 if (moreunits > 1) {
5813 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005814 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005815 /* integer overflow */
5816 PyErr_NoMemory();
5817 goto error;
5818 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005819 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005820 goto error;
5821 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5822 }
5823
5824 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005825 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005826 out += moreunits;
5827 } else /* rep is unicode */ {
5828 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5829 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5830 &out, native_ordering);
5831 }
5832
5833 Py_CLEAR(rep);
5834 }
5835
5836 /* Cut back to size actually needed. This is necessary for, for example,
5837 encoding of a string containing isolated surrogates and the 'ignore' handler
5838 is used. */
5839 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5840 if (nsize != PyBytes_GET_SIZE(v))
5841 _PyBytes_Resize(&v, nsize);
5842 Py_XDECREF(errorHandler);
5843 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005844 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005845 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005846 error:
5847 Py_XDECREF(rep);
5848 Py_XDECREF(errorHandler);
5849 Py_XDECREF(exc);
5850 Py_XDECREF(v);
5851 return NULL;
5852#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853}
5854
Alexander Belopolsky40018472011-02-26 01:02:56 +00005855PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005856PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5857 Py_ssize_t size,
5858 const char *errors,
5859 int byteorder)
5860{
5861 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005862 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005863 if (tmp == NULL)
5864 return NULL;
5865 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5866 Py_DECREF(tmp);
5867 return result;
5868}
5869
5870PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005871PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005873 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874}
5875
5876/* --- Unicode Escape Codec ----------------------------------------------- */
5877
Fredrik Lundh06d12682001-01-24 07:59:11 +00005878static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005879
Alexander Belopolsky40018472011-02-26 01:02:56 +00005880PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005881_PyUnicode_DecodeUnicodeEscape(const char *s,
5882 Py_ssize_t size,
5883 const char *errors,
5884 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005886 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005887 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005889 PyObject *errorHandler = NULL;
5890 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005891
Eric V. Smith42454af2016-10-31 09:22:08 -04005892 // so we can remember if we've seen an invalid escape char or not
5893 *first_invalid_escape = NULL;
5894
Victor Stinner62ec3312016-09-06 17:04:34 -07005895 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005896 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005897 }
5898 /* Escaped strings will always be longer than the resulting
5899 Unicode string, so we start with size here and then reduce the
5900 length after conversion to the true value.
5901 (but if the error callback returns a long replacement string
5902 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005903 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005904 writer.min_length = size;
5905 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5906 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005907 }
5908
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909 end = s + size;
5910 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005911 unsigned char c = (unsigned char) *s++;
5912 Py_UCS4 ch;
5913 int count;
5914 Py_ssize_t startinpos;
5915 Py_ssize_t endinpos;
5916 const char *message;
5917
5918#define WRITE_ASCII_CHAR(ch) \
5919 do { \
5920 assert(ch <= 127); \
5921 assert(writer.pos < writer.size); \
5922 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5923 } while(0)
5924
5925#define WRITE_CHAR(ch) \
5926 do { \
5927 if (ch <= writer.maxchar) { \
5928 assert(writer.pos < writer.size); \
5929 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5930 } \
5931 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5932 goto onError; \
5933 } \
5934 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935
5936 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005937 if (c != '\\') {
5938 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939 continue;
5940 }
5941
Victor Stinner62ec3312016-09-06 17:04:34 -07005942 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005943 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005944 if (s >= end) {
5945 message = "\\ at end of string";
5946 goto error;
5947 }
5948 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005949
Victor Stinner62ec3312016-09-06 17:04:34 -07005950 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005951 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952
Benjamin Peterson29060642009-01-31 22:14:21 +00005953 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005954 case '\n': continue;
5955 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5956 case '\'': WRITE_ASCII_CHAR('\''); continue;
5957 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5958 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005959 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005960 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5961 case 't': WRITE_ASCII_CHAR('\t'); continue;
5962 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5963 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005964 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005965 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005966 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005967 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968
Benjamin Peterson29060642009-01-31 22:14:21 +00005969 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970 case '0': case '1': case '2': case '3':
5971 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005972 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005973 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005974 ch = (ch<<3) + *s++ - '0';
5975 if (s < end && '0' <= *s && *s <= '7') {
5976 ch = (ch<<3) + *s++ - '0';
5977 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005979 WRITE_CHAR(ch);
5980 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005981
Benjamin Peterson29060642009-01-31 22:14:21 +00005982 /* hex escapes */
5983 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005984 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005985 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005986 message = "truncated \\xXX escape";
5987 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988
Benjamin Peterson29060642009-01-31 22:14:21 +00005989 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005991 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005992 message = "truncated \\uXXXX escape";
5993 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005994
Benjamin Peterson29060642009-01-31 22:14:21 +00005995 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005996 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005997 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005998 message = "truncated \\UXXXXXXXX escape";
5999 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006000 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006001 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006002 ch <<= 4;
6003 if (c >= '0' && c <= '9') {
6004 ch += c - '0';
6005 }
6006 else if (c >= 'a' && c <= 'f') {
6007 ch += c - ('a' - 10);
6008 }
6009 else if (c >= 'A' && c <= 'F') {
6010 ch += c - ('A' - 10);
6011 }
6012 else {
6013 break;
6014 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006015 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006016 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006017 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006018 }
6019
6020 /* when we get here, ch is a 32-bit unicode character */
6021 if (ch > MAX_UNICODE) {
6022 message = "illegal Unicode character";
6023 goto error;
6024 }
6025
6026 WRITE_CHAR(ch);
6027 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006028
Benjamin Peterson29060642009-01-31 22:14:21 +00006029 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006030 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006031 if (ucnhash_CAPI == NULL) {
6032 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006033 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6034 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006035 if (ucnhash_CAPI == NULL) {
6036 PyErr_SetString(
6037 PyExc_UnicodeError,
6038 "\\N escapes not supported (can't load unicodedata module)"
6039 );
6040 goto onError;
6041 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006042 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006043
6044 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006045 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006046 const char *start = ++s;
6047 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006048 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006049 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006050 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006051 namelen = s - start;
6052 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006053 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006055 ch = 0xffffffff; /* in case 'getcode' messes up */
6056 if (namelen <= INT_MAX &&
6057 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6058 &ch, 0)) {
6059 assert(ch <= MAX_UNICODE);
6060 WRITE_CHAR(ch);
6061 continue;
6062 }
6063 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006064 }
6065 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006066 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006067
6068 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006069 if (*first_invalid_escape == NULL) {
6070 *first_invalid_escape = s-1; /* Back up one char, since we've
6071 already incremented s. */
6072 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006073 WRITE_ASCII_CHAR('\\');
6074 WRITE_CHAR(c);
6075 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006077
6078 error:
6079 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006080 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006081 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006082 errors, &errorHandler,
6083 "unicodeescape", message,
6084 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006085 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006086 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006087 }
Miss Islington (bot)09819ef2018-02-12 23:15:57 -08006088 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006089
6090#undef WRITE_ASCII_CHAR
6091#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006093
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006094 Py_XDECREF(errorHandler);
6095 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006096 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006097
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006099 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006100 Py_XDECREF(errorHandler);
6101 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102 return NULL;
6103}
6104
Eric V. Smith42454af2016-10-31 09:22:08 -04006105PyObject *
6106PyUnicode_DecodeUnicodeEscape(const char *s,
6107 Py_ssize_t size,
6108 const char *errors)
6109{
6110 const char *first_invalid_escape;
6111 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6112 &first_invalid_escape);
6113 if (result == NULL)
6114 return NULL;
6115 if (first_invalid_escape != NULL) {
6116 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6117 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006118 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006119 Py_DECREF(result);
6120 return NULL;
6121 }
6122 }
6123 return result;
6124}
6125
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006126/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006127
Alexander Belopolsky40018472011-02-26 01:02:56 +00006128PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006129PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006131 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006132 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006134 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006135 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006136 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006137
Ezio Melottie7f90372012-10-05 03:33:31 +03006138 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006139 escape.
6140
Ezio Melottie7f90372012-10-05 03:33:31 +03006141 For UCS1 strings it's '\xxx', 4 bytes per source character.
6142 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6143 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006144 */
6145
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006146 if (!PyUnicode_Check(unicode)) {
6147 PyErr_BadArgument();
6148 return NULL;
6149 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006150 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006151 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006152 }
Victor Stinner358af132015-10-12 22:36:57 +02006153
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006155 if (len == 0) {
6156 return PyBytes_FromStringAndSize(NULL, 0);
6157 }
6158
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006159 kind = PyUnicode_KIND(unicode);
6160 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006161 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6162 bytes, and 1 byte characters 4. */
6163 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006164 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006165 return PyErr_NoMemory();
6166 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006167 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006168 if (repr == NULL) {
6169 return NULL;
6170 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171
Victor Stinner62ec3312016-09-06 17:04:34 -07006172 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006173 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006174 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006175
Victor Stinner62ec3312016-09-06 17:04:34 -07006176 /* U+0000-U+00ff range */
6177 if (ch < 0x100) {
6178 if (ch >= ' ' && ch < 127) {
6179 if (ch != '\\') {
6180 /* Copy printable US ASCII as-is */
6181 *p++ = (char) ch;
6182 }
6183 /* Escape backslashes */
6184 else {
6185 *p++ = '\\';
6186 *p++ = '\\';
6187 }
6188 }
Victor Stinner358af132015-10-12 22:36:57 +02006189
Victor Stinner62ec3312016-09-06 17:04:34 -07006190 /* Map special whitespace to '\t', \n', '\r' */
6191 else if (ch == '\t') {
6192 *p++ = '\\';
6193 *p++ = 't';
6194 }
6195 else if (ch == '\n') {
6196 *p++ = '\\';
6197 *p++ = 'n';
6198 }
6199 else if (ch == '\r') {
6200 *p++ = '\\';
6201 *p++ = 'r';
6202 }
6203
6204 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6205 else {
6206 *p++ = '\\';
6207 *p++ = 'x';
6208 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6209 *p++ = Py_hexdigits[ch & 0x000F];
6210 }
Tim Petersced69f82003-09-16 20:30:58 +00006211 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006212 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006213 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214 *p++ = '\\';
6215 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006216 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6217 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6218 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6219 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006221 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6222 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006223
Victor Stinner62ec3312016-09-06 17:04:34 -07006224 /* Make sure that the first two digits are zero */
6225 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006226 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006227 *p++ = 'U';
6228 *p++ = '0';
6229 *p++ = '0';
6230 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6231 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6232 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6233 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6234 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6235 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006236 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238
Victor Stinner62ec3312016-09-06 17:04:34 -07006239 assert(p - PyBytes_AS_STRING(repr) > 0);
6240 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6241 return NULL;
6242 }
6243 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244}
6245
Alexander Belopolsky40018472011-02-26 01:02:56 +00006246PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006247PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6248 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006250 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006251 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006252 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006253 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006254 }
6255
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006256 result = PyUnicode_AsUnicodeEscapeString(tmp);
6257 Py_DECREF(tmp);
6258 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006259}
6260
6261/* --- Raw Unicode Escape Codec ------------------------------------------- */
6262
Alexander Belopolsky40018472011-02-26 01:02:56 +00006263PyObject *
6264PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006265 Py_ssize_t size,
6266 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006267{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006268 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006269 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006270 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006271 PyObject *errorHandler = NULL;
6272 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006273
Victor Stinner62ec3312016-09-06 17:04:34 -07006274 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006275 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006276 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006277
Guido van Rossumd57fd912000-03-10 22:53:23 +00006278 /* Escaped strings will always be longer than the resulting
6279 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006280 length after conversion to the true value. (But decoding error
6281 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006282 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006283 writer.min_length = size;
6284 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6285 goto onError;
6286 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006287
Guido van Rossumd57fd912000-03-10 22:53:23 +00006288 end = s + size;
6289 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006290 unsigned char c = (unsigned char) *s++;
6291 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006292 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006293 Py_ssize_t startinpos;
6294 Py_ssize_t endinpos;
6295 const char *message;
6296
6297#define WRITE_CHAR(ch) \
6298 do { \
6299 if (ch <= writer.maxchar) { \
6300 assert(writer.pos < writer.size); \
6301 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6302 } \
6303 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6304 goto onError; \
6305 } \
6306 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307
Benjamin Peterson29060642009-01-31 22:14:21 +00006308 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006309 if (c != '\\' || s >= end) {
6310 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006311 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006312 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006313
Victor Stinner62ec3312016-09-06 17:04:34 -07006314 c = (unsigned char) *s++;
6315 if (c == 'u') {
6316 count = 4;
6317 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006318 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006319 else if (c == 'U') {
6320 count = 8;
6321 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006322 }
6323 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006324 assert(writer.pos < writer.size);
6325 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6326 WRITE_CHAR(c);
6327 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006328 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006329 startinpos = s - starts - 2;
6330
6331 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6332 for (ch = 0; count && s < end; ++s, --count) {
6333 c = (unsigned char)*s;
6334 ch <<= 4;
6335 if (c >= '0' && c <= '9') {
6336 ch += c - '0';
6337 }
6338 else if (c >= 'a' && c <= 'f') {
6339 ch += c - ('a' - 10);
6340 }
6341 else if (c >= 'A' && c <= 'F') {
6342 ch += c - ('A' - 10);
6343 }
6344 else {
6345 break;
6346 }
6347 }
6348 if (!count) {
6349 if (ch <= MAX_UNICODE) {
6350 WRITE_CHAR(ch);
6351 continue;
6352 }
6353 message = "\\Uxxxxxxxx out of range";
6354 }
6355
6356 endinpos = s-starts;
6357 writer.min_length = end - s + writer.pos;
6358 if (unicode_decode_call_errorhandler_writer(
6359 errors, &errorHandler,
6360 "rawunicodeescape", message,
6361 &starts, &end, &startinpos, &endinpos, &exc, &s,
6362 &writer)) {
6363 goto onError;
6364 }
Miss Islington (bot)09819ef2018-02-12 23:15:57 -08006365 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006366
6367#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006368 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006369 Py_XDECREF(errorHandler);
6370 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006371 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006372
Benjamin Peterson29060642009-01-31 22:14:21 +00006373 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006374 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006375 Py_XDECREF(errorHandler);
6376 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006377 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006378
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379}
6380
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006381
Alexander Belopolsky40018472011-02-26 01:02:56 +00006382PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006383PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006384{
Victor Stinner62ec3312016-09-06 17:04:34 -07006385 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006387 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006388 int kind;
6389 void *data;
6390 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006391
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392 if (!PyUnicode_Check(unicode)) {
6393 PyErr_BadArgument();
6394 return NULL;
6395 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006396 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006397 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006398 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006399 kind = PyUnicode_KIND(unicode);
6400 data = PyUnicode_DATA(unicode);
6401 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006402 if (kind == PyUnicode_1BYTE_KIND) {
6403 return PyBytes_FromStringAndSize(data, len);
6404 }
Victor Stinner0e368262011-11-10 20:12:49 +01006405
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6407 bytes, and 1 byte characters 4. */
6408 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006409
Victor Stinner62ec3312016-09-06 17:04:34 -07006410 if (len > PY_SSIZE_T_MAX / expandsize) {
6411 return PyErr_NoMemory();
6412 }
6413 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6414 if (repr == NULL) {
6415 return NULL;
6416 }
6417 if (len == 0) {
6418 return repr;
6419 }
6420
6421 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006422 for (pos = 0; pos < len; pos++) {
6423 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006424
Victor Stinner62ec3312016-09-06 17:04:34 -07006425 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6426 if (ch < 0x100) {
6427 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006428 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006429 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6430 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006431 *p++ = '\\';
6432 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006433 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6434 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6435 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6436 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006437 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006438 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6439 else {
6440 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6441 *p++ = '\\';
6442 *p++ = 'U';
6443 *p++ = '0';
6444 *p++ = '0';
6445 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6446 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6447 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6448 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6449 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6450 *p++ = Py_hexdigits[ch & 15];
6451 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006452 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006453
Victor Stinner62ec3312016-09-06 17:04:34 -07006454 assert(p > PyBytes_AS_STRING(repr));
6455 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6456 return NULL;
6457 }
6458 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006459}
6460
Alexander Belopolsky40018472011-02-26 01:02:56 +00006461PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006462PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6463 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006464{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006465 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006466 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006467 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006468 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006469 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6470 Py_DECREF(tmp);
6471 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006472}
6473
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006474/* --- Unicode Internal Codec ------------------------------------------- */
6475
Alexander Belopolsky40018472011-02-26 01:02:56 +00006476PyObject *
6477_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006478 Py_ssize_t size,
6479 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006480{
6481 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006482 Py_ssize_t startinpos;
6483 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006484 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006485 const char *end;
6486 const char *reason;
6487 PyObject *errorHandler = NULL;
6488 PyObject *exc = NULL;
6489
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006490 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006491 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006492 1))
6493 return NULL;
6494
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006495 if (size < 0) {
6496 PyErr_BadInternalCall();
6497 return NULL;
6498 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006499 if (size == 0)
6500 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006501
Victor Stinner8f674cc2013-04-17 23:02:17 +02006502 _PyUnicodeWriter_Init(&writer);
6503 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6504 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006506 }
6507 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006508
Victor Stinner8f674cc2013-04-17 23:02:17 +02006509 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006510 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006511 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006512 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006513 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006514 endinpos = end-starts;
6515 reason = "truncated input";
6516 goto error;
6517 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006518 /* We copy the raw representation one byte at a time because the
6519 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006520 ((char *) &uch)[0] = s[0];
6521 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006522#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006523 ((char *) &uch)[2] = s[2];
6524 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006525#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006526 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006527#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006528 /* We have to sanity check the raw data, otherwise doom looms for
6529 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006530 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006531 endinpos = s - starts + Py_UNICODE_SIZE;
6532 reason = "illegal code point (> 0x10FFFF)";
6533 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006534 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006535#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006536 s += Py_UNICODE_SIZE;
6537#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006538 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006539 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006540 Py_UNICODE uch2;
6541 ((char *) &uch2)[0] = s[0];
6542 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006543 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006544 {
Victor Stinner551ac952011-11-29 22:58:13 +01006545 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006546 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006547 }
6548 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006549#endif
6550
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006551 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006552 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006553 continue;
6554
6555 error:
6556 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006557 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006558 errors, &errorHandler,
6559 "unicode_internal", reason,
6560 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006561 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006562 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006563 }
6564
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006565 Py_XDECREF(errorHandler);
6566 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006567 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006568
Benjamin Peterson29060642009-01-31 22:14:21 +00006569 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006570 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006571 Py_XDECREF(errorHandler);
6572 Py_XDECREF(exc);
6573 return NULL;
6574}
6575
Guido van Rossumd57fd912000-03-10 22:53:23 +00006576/* --- Latin-1 Codec ------------------------------------------------------ */
6577
Alexander Belopolsky40018472011-02-26 01:02:56 +00006578PyObject *
6579PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006580 Py_ssize_t size,
6581 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006582{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006583 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006584 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006585}
6586
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006588static void
6589make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006590 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006591 PyObject *unicode,
6592 Py_ssize_t startpos, Py_ssize_t endpos,
6593 const char *reason)
6594{
6595 if (*exceptionObject == NULL) {
6596 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006597 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006598 encoding, unicode, startpos, endpos, reason);
6599 }
6600 else {
6601 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6602 goto onError;
6603 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6604 goto onError;
6605 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6606 goto onError;
6607 return;
6608 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006609 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006610 }
6611}
6612
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006613/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006614static void
6615raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006616 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006617 PyObject *unicode,
6618 Py_ssize_t startpos, Py_ssize_t endpos,
6619 const char *reason)
6620{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006621 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006622 encoding, unicode, startpos, endpos, reason);
6623 if (*exceptionObject != NULL)
6624 PyCodec_StrictErrors(*exceptionObject);
6625}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006626
6627/* error handling callback helper:
6628 build arguments, call the callback and check the arguments,
6629 put the result into newpos and return the replacement string, which
6630 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006631static PyObject *
6632unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006633 PyObject **errorHandler,
6634 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006636 Py_ssize_t startpos, Py_ssize_t endpos,
6637 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006638{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006639 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006640 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006641 PyObject *restuple;
6642 PyObject *resunicode;
6643
6644 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006646 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006647 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006648 }
6649
Benjamin Petersonbac79492012-01-14 13:34:47 -05006650 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 return NULL;
6652 len = PyUnicode_GET_LENGTH(unicode);
6653
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006654 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006655 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006656 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006658
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006659 restuple = PyObject_CallFunctionObjArgs(
6660 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006661 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006664 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 Py_DECREF(restuple);
6666 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006667 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006668 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006669 &resunicode, newpos)) {
6670 Py_DECREF(restuple);
6671 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006672 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006673 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6674 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6675 Py_DECREF(restuple);
6676 return NULL;
6677 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006678 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006679 *newpos = len + *newpos;
6680 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006681 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006682 Py_DECREF(restuple);
6683 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006684 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006685 Py_INCREF(resunicode);
6686 Py_DECREF(restuple);
6687 return resunicode;
6688}
6689
Alexander Belopolsky40018472011-02-26 01:02:56 +00006690static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006691unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006692 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006693 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006694{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006695 /* input state */
6696 Py_ssize_t pos=0, size;
6697 int kind;
6698 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006699 /* pointer into the output */
6700 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006701 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6702 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006703 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006705 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006706 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006707 /* output object */
6708 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006709
Benjamin Petersonbac79492012-01-14 13:34:47 -05006710 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006711 return NULL;
6712 size = PyUnicode_GET_LENGTH(unicode);
6713 kind = PyUnicode_KIND(unicode);
6714 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006715 /* allocate enough for a simple encoding without
6716 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006717 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006718 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006719
6720 _PyBytesWriter_Init(&writer);
6721 str = _PyBytesWriter_Alloc(&writer, size);
6722 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006723 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006724
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006725 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006726 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006727
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006729 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006731 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006732 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006733 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006735 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006737 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006738 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006740
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006741 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006743
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006744 /* Only overallocate the buffer if it's not the last write */
6745 writer.overallocate = (collend < size);
6746
Benjamin Peterson29060642009-01-31 22:14:21 +00006747 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006748 if (error_handler == _Py_ERROR_UNKNOWN)
6749 error_handler = get_error_handler(errors);
6750
6751 switch (error_handler) {
6752 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006753 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006754 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006755
6756 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006757 memset(str, '?', collend - collstart);
6758 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006759 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006760 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006761 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006762 break;
Victor Stinner50149202015-09-22 00:26:54 +02006763
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006764 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006765 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006766 writer.min_size -= (collend - collstart);
6767 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006768 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006769 if (str == NULL)
6770 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006771 pos = collend;
6772 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006773
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006774 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006775 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006776 writer.min_size -= (collend - collstart);
6777 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006778 unicode, collstart, collend);
6779 if (str == NULL)
6780 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006781 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 break;
Victor Stinner50149202015-09-22 00:26:54 +02006783
Victor Stinnerc3713e92015-09-29 12:32:13 +02006784 case _Py_ERROR_SURROGATEESCAPE:
6785 for (i = collstart; i < collend; ++i) {
6786 ch = PyUnicode_READ(kind, data, i);
6787 if (ch < 0xdc80 || 0xdcff < ch) {
6788 /* Not a UTF-8b surrogate */
6789 break;
6790 }
6791 *str++ = (char)(ch - 0xdc00);
6792 ++pos;
6793 }
6794 if (i >= collend)
6795 break;
6796 collstart = pos;
6797 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006798 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006799
Benjamin Peterson29060642009-01-31 22:14:21 +00006800 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006801 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6802 encoding, reason, unicode, &exc,
6803 collstart, collend, &newpos);
6804 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006805 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006806
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006807 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006808 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006809
Victor Stinner6bd525b2015-10-09 13:10:05 +02006810 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006811 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006812 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006813 PyBytes_AS_STRING(rep),
6814 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006815 if (str == NULL)
6816 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006817 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006818 else {
6819 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006820
Victor Stinner6bd525b2015-10-09 13:10:05 +02006821 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006822 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006823
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006824 if (limit == 256 ?
6825 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6826 !PyUnicode_IS_ASCII(rep))
6827 {
6828 /* Not all characters are smaller than limit */
6829 raise_encode_exception(&exc, encoding, unicode,
6830 collstart, collend, reason);
6831 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006832 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006833 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6834 str = _PyBytesWriter_WriteBytes(&writer, str,
6835 PyUnicode_DATA(rep),
6836 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006837 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006838 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006839 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006840 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006841
6842 /* If overallocation was disabled, ensure that it was the last
6843 write. Otherwise, we missed an optimization */
6844 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006845 }
6846 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006847
Victor Stinner50149202015-09-22 00:26:54 +02006848 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006849 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006850 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006851
6852 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006853 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006854 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006855 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006856 Py_XDECREF(exc);
6857 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006858}
6859
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006860/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006861PyObject *
6862PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006863 Py_ssize_t size,
6864 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006865{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006866 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006867 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006868 if (unicode == NULL)
6869 return NULL;
6870 result = unicode_encode_ucs1(unicode, errors, 256);
6871 Py_DECREF(unicode);
6872 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006873}
6874
Alexander Belopolsky40018472011-02-26 01:02:56 +00006875PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006876_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006877{
6878 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 PyErr_BadArgument();
6880 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006881 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006882 if (PyUnicode_READY(unicode) == -1)
6883 return NULL;
6884 /* Fast path: if it is a one-byte string, construct
6885 bytes object directly. */
6886 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6887 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6888 PyUnicode_GET_LENGTH(unicode));
6889 /* Non-Latin-1 characters present. Defer to above function to
6890 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006891 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006892}
6893
6894PyObject*
6895PyUnicode_AsLatin1String(PyObject *unicode)
6896{
6897 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006898}
6899
6900/* --- 7-bit ASCII Codec -------------------------------------------------- */
6901
Alexander Belopolsky40018472011-02-26 01:02:56 +00006902PyObject *
6903PyUnicode_DecodeASCII(const char *s,
6904 Py_ssize_t size,
6905 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006906{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006907 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006908 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006909 int kind;
6910 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006911 Py_ssize_t startinpos;
6912 Py_ssize_t endinpos;
6913 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006914 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006915 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006916 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006917 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006918
Guido van Rossumd57fd912000-03-10 22:53:23 +00006919 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006920 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006921
Guido van Rossumd57fd912000-03-10 22:53:23 +00006922 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006923 if (size == 1 && (unsigned char)s[0] < 128)
6924 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006925
Victor Stinner8f674cc2013-04-17 23:02:17 +02006926 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006927 writer.min_length = size;
6928 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006929 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006930
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006931 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006932 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006933 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006934 writer.pos = outpos;
6935 if (writer.pos == size)
6936 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006937
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006938 s += writer.pos;
6939 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006940 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006941 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006942 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006943 PyUnicode_WRITE(kind, data, writer.pos, c);
6944 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006945 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006946 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006947 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006948
6949 /* byte outsize range 0x00..0x7f: call the error handler */
6950
6951 if (error_handler == _Py_ERROR_UNKNOWN)
6952 error_handler = get_error_handler(errors);
6953
6954 switch (error_handler)
6955 {
6956 case _Py_ERROR_REPLACE:
6957 case _Py_ERROR_SURROGATEESCAPE:
6958 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006959 but we may switch to UCS2 at the first write */
6960 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6961 goto onError;
6962 kind = writer.kind;
6963 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006964
6965 if (error_handler == _Py_ERROR_REPLACE)
6966 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6967 else
6968 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6969 writer.pos++;
6970 ++s;
6971 break;
6972
6973 case _Py_ERROR_IGNORE:
6974 ++s;
6975 break;
6976
6977 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 startinpos = s-starts;
6979 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006980 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006981 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006982 "ascii", "ordinal not in range(128)",
6983 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006984 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006985 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006986 kind = writer.kind;
6987 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006988 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006989 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006990 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006991 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006992 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006993
Benjamin Peterson29060642009-01-31 22:14:21 +00006994 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006995 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006996 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006997 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006998 return NULL;
6999}
7000
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007001/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007002PyObject *
7003PyUnicode_EncodeASCII(const Py_UNICODE *p,
7004 Py_ssize_t size,
7005 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007006{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007007 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007008 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007009 if (unicode == NULL)
7010 return NULL;
7011 result = unicode_encode_ucs1(unicode, errors, 128);
7012 Py_DECREF(unicode);
7013 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007014}
7015
Alexander Belopolsky40018472011-02-26 01:02:56 +00007016PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007017_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007018{
7019 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007020 PyErr_BadArgument();
7021 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007022 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007023 if (PyUnicode_READY(unicode) == -1)
7024 return NULL;
7025 /* Fast path: if it is an ASCII-only string, construct bytes object
7026 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007027 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007028 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7029 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007030 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007031}
7032
7033PyObject *
7034PyUnicode_AsASCIIString(PyObject *unicode)
7035{
7036 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007037}
7038
Steve Dowercc16be82016-09-08 10:35:16 -07007039#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007040
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007041/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007042
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007043#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007044#define NEED_RETRY
7045#endif
7046
Victor Stinner3a50e702011-10-18 21:21:00 +02007047#ifndef WC_ERR_INVALID_CHARS
7048# define WC_ERR_INVALID_CHARS 0x0080
7049#endif
7050
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007051static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007052code_page_name(UINT code_page, PyObject **obj)
7053{
7054 *obj = NULL;
7055 if (code_page == CP_ACP)
7056 return "mbcs";
7057 if (code_page == CP_UTF7)
7058 return "CP_UTF7";
7059 if (code_page == CP_UTF8)
7060 return "CP_UTF8";
7061
7062 *obj = PyBytes_FromFormat("cp%u", code_page);
7063 if (*obj == NULL)
7064 return NULL;
7065 return PyBytes_AS_STRING(*obj);
7066}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007067
Victor Stinner3a50e702011-10-18 21:21:00 +02007068static DWORD
7069decode_code_page_flags(UINT code_page)
7070{
7071 if (code_page == CP_UTF7) {
7072 /* The CP_UTF7 decoder only supports flags=0 */
7073 return 0;
7074 }
7075 else
7076 return MB_ERR_INVALID_CHARS;
7077}
7078
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007080 * Decode a byte string from a Windows code page into unicode object in strict
7081 * mode.
7082 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007083 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7084 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007085 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007086static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007087decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007088 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007089 const char *in,
7090 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007091{
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007093 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095
7096 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 assert(insize > 0);
7098 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7099 if (outsize <= 0)
7100 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007101
7102 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007103 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007104 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007105 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007106 if (*v == NULL)
7107 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109 }
7110 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007111 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007113 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007114 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007115 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116 }
7117
7118 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007119 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7120 if (outsize <= 0)
7121 goto error;
7122 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007123
Victor Stinner3a50e702011-10-18 21:21:00 +02007124error:
7125 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7126 return -2;
7127 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007128 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007129}
7130
Victor Stinner3a50e702011-10-18 21:21:00 +02007131/*
7132 * Decode a byte string from a code page into unicode object with an error
7133 * handler.
7134 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007135 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007136 * UnicodeDecodeError exception and returns -1 on error.
7137 */
7138static int
7139decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007140 PyObject **v,
7141 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007142 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007143{
7144 const char *startin = in;
7145 const char *endin = in + size;
7146 const DWORD flags = decode_code_page_flags(code_page);
7147 /* Ideally, we should get reason from FormatMessage. This is the Windows
7148 2000 English version of the message. */
7149 const char *reason = "No mapping for the Unicode character exists "
7150 "in the target code page.";
7151 /* each step cannot decode more than 1 character, but a character can be
7152 represented as a surrogate pair */
7153 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007154 int insize;
7155 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007156 PyObject *errorHandler = NULL;
7157 PyObject *exc = NULL;
7158 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007159 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007160 DWORD err;
7161 int ret = -1;
7162
7163 assert(size > 0);
7164
7165 encoding = code_page_name(code_page, &encoding_obj);
7166 if (encoding == NULL)
7167 return -1;
7168
Victor Stinner7d00cc12014-03-17 23:08:06 +01007169 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007170 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7171 UnicodeDecodeError. */
7172 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7173 if (exc != NULL) {
7174 PyCodec_StrictErrors(exc);
7175 Py_CLEAR(exc);
7176 }
7177 goto error;
7178 }
7179
7180 if (*v == NULL) {
7181 /* Create unicode object */
7182 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7183 PyErr_NoMemory();
7184 goto error;
7185 }
Victor Stinnerab595942011-12-17 04:59:06 +01007186 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007187 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 if (*v == NULL)
7189 goto error;
7190 startout = PyUnicode_AS_UNICODE(*v);
7191 }
7192 else {
7193 /* Extend unicode object */
7194 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7195 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7196 PyErr_NoMemory();
7197 goto error;
7198 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007199 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007200 goto error;
7201 startout = PyUnicode_AS_UNICODE(*v) + n;
7202 }
7203
7204 /* Decode the byte string character per character */
7205 out = startout;
7206 while (in < endin)
7207 {
7208 /* Decode a character */
7209 insize = 1;
7210 do
7211 {
7212 outsize = MultiByteToWideChar(code_page, flags,
7213 in, insize,
7214 buffer, Py_ARRAY_LENGTH(buffer));
7215 if (outsize > 0)
7216 break;
7217 err = GetLastError();
7218 if (err != ERROR_NO_UNICODE_TRANSLATION
7219 && err != ERROR_INSUFFICIENT_BUFFER)
7220 {
7221 PyErr_SetFromWindowsErr(0);
7222 goto error;
7223 }
7224 insize++;
7225 }
7226 /* 4=maximum length of a UTF-8 sequence */
7227 while (insize <= 4 && (in + insize) <= endin);
7228
7229 if (outsize <= 0) {
7230 Py_ssize_t startinpos, endinpos, outpos;
7231
Victor Stinner7d00cc12014-03-17 23:08:06 +01007232 /* last character in partial decode? */
7233 if (in + insize >= endin && !final)
7234 break;
7235
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 startinpos = in - startin;
7237 endinpos = startinpos + 1;
7238 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007239 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 errors, &errorHandler,
7241 encoding, reason,
7242 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007243 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 {
7245 goto error;
7246 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007247 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007248 }
7249 else {
7250 in += insize;
7251 memcpy(out, buffer, outsize * sizeof(wchar_t));
7252 out += outsize;
7253 }
7254 }
7255
7256 /* write a NUL character at the end */
7257 *out = 0;
7258
7259 /* Extend unicode object */
7260 outsize = out - startout;
7261 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007262 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007263 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007264 /* (in - startin) <= size and size is an int */
7265 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007266
7267error:
7268 Py_XDECREF(encoding_obj);
7269 Py_XDECREF(errorHandler);
7270 Py_XDECREF(exc);
7271 return ret;
7272}
7273
Victor Stinner3a50e702011-10-18 21:21:00 +02007274static PyObject *
7275decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007276 const char *s, Py_ssize_t size,
7277 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007278{
Victor Stinner76a31a62011-11-04 00:05:13 +01007279 PyObject *v = NULL;
7280 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007281
Victor Stinner3a50e702011-10-18 21:21:00 +02007282 if (code_page < 0) {
7283 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7284 return NULL;
7285 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007286 if (size < 0) {
7287 PyErr_BadInternalCall();
7288 return NULL;
7289 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007290
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007291 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007292 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007293
Victor Stinner76a31a62011-11-04 00:05:13 +01007294 do
7295 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007296#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007297 if (size > INT_MAX) {
7298 chunk_size = INT_MAX;
7299 final = 0;
7300 done = 0;
7301 }
7302 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007303#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007304 {
7305 chunk_size = (int)size;
7306 final = (consumed == NULL);
7307 done = 1;
7308 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007309
Victor Stinner76a31a62011-11-04 00:05:13 +01007310 if (chunk_size == 0 && done) {
7311 if (v != NULL)
7312 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007313 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007314 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007315
Victor Stinner76a31a62011-11-04 00:05:13 +01007316 converted = decode_code_page_strict(code_page, &v,
7317 s, chunk_size);
7318 if (converted == -2)
7319 converted = decode_code_page_errors(code_page, &v,
7320 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007321 errors, final);
7322 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007323
7324 if (converted < 0) {
7325 Py_XDECREF(v);
7326 return NULL;
7327 }
7328
7329 if (consumed)
7330 *consumed += converted;
7331
7332 s += converted;
7333 size -= converted;
7334 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007335
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007336 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007337}
7338
Alexander Belopolsky40018472011-02-26 01:02:56 +00007339PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007340PyUnicode_DecodeCodePageStateful(int code_page,
7341 const char *s,
7342 Py_ssize_t size,
7343 const char *errors,
7344 Py_ssize_t *consumed)
7345{
7346 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7347}
7348
7349PyObject *
7350PyUnicode_DecodeMBCSStateful(const char *s,
7351 Py_ssize_t size,
7352 const char *errors,
7353 Py_ssize_t *consumed)
7354{
7355 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7356}
7357
7358PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007359PyUnicode_DecodeMBCS(const char *s,
7360 Py_ssize_t size,
7361 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007362{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007363 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7364}
7365
Victor Stinner3a50e702011-10-18 21:21:00 +02007366static DWORD
7367encode_code_page_flags(UINT code_page, const char *errors)
7368{
7369 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007370 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007371 }
7372 else if (code_page == CP_UTF7) {
7373 /* CP_UTF7 only supports flags=0 */
7374 return 0;
7375 }
7376 else {
7377 if (errors != NULL && strcmp(errors, "replace") == 0)
7378 return 0;
7379 else
7380 return WC_NO_BEST_FIT_CHARS;
7381 }
7382}
7383
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007384/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007385 * Encode a Unicode string to a Windows code page into a byte string in strict
7386 * mode.
7387 *
7388 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007389 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007390 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007391static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007392encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007393 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007395{
Victor Stinner554f3f02010-06-16 23:33:54 +00007396 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007397 BOOL *pusedDefaultChar = &usedDefaultChar;
7398 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007399 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007400 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 const DWORD flags = encode_code_page_flags(code_page, NULL);
7402 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007403 /* Create a substring so that we can get the UTF-16 representation
7404 of just the slice under consideration. */
7405 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007406
Martin v. Löwis3d325192011-11-04 18:23:06 +01007407 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007408
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007410 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007412 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007413
Victor Stinner2fc507f2011-11-04 20:06:39 +01007414 substring = PyUnicode_Substring(unicode, offset, offset+len);
7415 if (substring == NULL)
7416 return -1;
7417 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7418 if (p == NULL) {
7419 Py_DECREF(substring);
7420 return -1;
7421 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007422 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007423
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007424 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007426 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007427 NULL, 0,
7428 NULL, pusedDefaultChar);
7429 if (outsize <= 0)
7430 goto error;
7431 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007432 if (pusedDefaultChar && *pusedDefaultChar) {
7433 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007435 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007436
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007438 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007440 if (*outbytes == NULL) {
7441 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007442 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007443 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007445 }
7446 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007447 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 const Py_ssize_t n = PyBytes_Size(*outbytes);
7449 if (outsize > PY_SSIZE_T_MAX - n) {
7450 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007451 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007452 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007454 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7455 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007457 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007459 }
7460
7461 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007463 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007464 out, outsize,
7465 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007466 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 if (outsize <= 0)
7468 goto error;
7469 if (pusedDefaultChar && *pusedDefaultChar)
7470 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007471 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007472
Victor Stinner3a50e702011-10-18 21:21:00 +02007473error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007474 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7476 return -2;
7477 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007478 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007479}
7480
Victor Stinner3a50e702011-10-18 21:21:00 +02007481/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007482 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 * error handler.
7484 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007485 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 * -1 on other error.
7487 */
7488static int
7489encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007490 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007491 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007492{
Victor Stinner3a50e702011-10-18 21:21:00 +02007493 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007494 Py_ssize_t pos = unicode_offset;
7495 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007496 /* Ideally, we should get reason from FormatMessage. This is the Windows
7497 2000 English version of the message. */
7498 const char *reason = "invalid character";
7499 /* 4=maximum length of a UTF-8 sequence */
7500 char buffer[4];
7501 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7502 Py_ssize_t outsize;
7503 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 PyObject *errorHandler = NULL;
7505 PyObject *exc = NULL;
7506 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007507 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007508 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007509 PyObject *rep;
7510 int ret = -1;
7511
7512 assert(insize > 0);
7513
7514 encoding = code_page_name(code_page, &encoding_obj);
7515 if (encoding == NULL)
7516 return -1;
7517
7518 if (errors == NULL || strcmp(errors, "strict") == 0) {
7519 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7520 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007521 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007522 if (exc != NULL) {
7523 PyCodec_StrictErrors(exc);
7524 Py_DECREF(exc);
7525 }
7526 Py_XDECREF(encoding_obj);
7527 return -1;
7528 }
7529
7530 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7531 pusedDefaultChar = &usedDefaultChar;
7532 else
7533 pusedDefaultChar = NULL;
7534
7535 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7536 PyErr_NoMemory();
7537 goto error;
7538 }
7539 outsize = insize * Py_ARRAY_LENGTH(buffer);
7540
7541 if (*outbytes == NULL) {
7542 /* Create string object */
7543 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7544 if (*outbytes == NULL)
7545 goto error;
7546 out = PyBytes_AS_STRING(*outbytes);
7547 }
7548 else {
7549 /* Extend string object */
7550 Py_ssize_t n = PyBytes_Size(*outbytes);
7551 if (n > PY_SSIZE_T_MAX - outsize) {
7552 PyErr_NoMemory();
7553 goto error;
7554 }
7555 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7556 goto error;
7557 out = PyBytes_AS_STRING(*outbytes) + n;
7558 }
7559
7560 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007561 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007562 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007563 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7564 wchar_t chars[2];
7565 int charsize;
7566 if (ch < 0x10000) {
7567 chars[0] = (wchar_t)ch;
7568 charsize = 1;
7569 }
7570 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007571 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7572 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007573 charsize = 2;
7574 }
7575
Victor Stinner3a50e702011-10-18 21:21:00 +02007576 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007577 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007578 buffer, Py_ARRAY_LENGTH(buffer),
7579 NULL, pusedDefaultChar);
7580 if (outsize > 0) {
7581 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7582 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007583 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007584 memcpy(out, buffer, outsize);
7585 out += outsize;
7586 continue;
7587 }
7588 }
7589 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7590 PyErr_SetFromWindowsErr(0);
7591 goto error;
7592 }
7593
Victor Stinner3a50e702011-10-18 21:21:00 +02007594 rep = unicode_encode_call_errorhandler(
7595 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007596 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007597 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007598 if (rep == NULL)
7599 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007600 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007601
7602 if (PyBytes_Check(rep)) {
7603 outsize = PyBytes_GET_SIZE(rep);
7604 if (outsize != 1) {
7605 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7606 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7607 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7608 Py_DECREF(rep);
7609 goto error;
7610 }
7611 out = PyBytes_AS_STRING(*outbytes) + offset;
7612 }
7613 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7614 out += outsize;
7615 }
7616 else {
7617 Py_ssize_t i;
7618 enum PyUnicode_Kind kind;
7619 void *data;
7620
Benjamin Petersonbac79492012-01-14 13:34:47 -05007621 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007622 Py_DECREF(rep);
7623 goto error;
7624 }
7625
7626 outsize = PyUnicode_GET_LENGTH(rep);
7627 if (outsize != 1) {
7628 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7629 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7630 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7631 Py_DECREF(rep);
7632 goto error;
7633 }
7634 out = PyBytes_AS_STRING(*outbytes) + offset;
7635 }
7636 kind = PyUnicode_KIND(rep);
7637 data = PyUnicode_DATA(rep);
7638 for (i=0; i < outsize; i++) {
7639 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7640 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007641 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007642 encoding, unicode,
7643 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007644 "unable to encode error handler result to ASCII");
7645 Py_DECREF(rep);
7646 goto error;
7647 }
7648 *out = (unsigned char)ch;
7649 out++;
7650 }
7651 }
7652 Py_DECREF(rep);
7653 }
7654 /* write a NUL byte */
7655 *out = 0;
7656 outsize = out - PyBytes_AS_STRING(*outbytes);
7657 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7658 if (_PyBytes_Resize(outbytes, outsize) < 0)
7659 goto error;
7660 ret = 0;
7661
7662error:
7663 Py_XDECREF(encoding_obj);
7664 Py_XDECREF(errorHandler);
7665 Py_XDECREF(exc);
7666 return ret;
7667}
7668
Victor Stinner3a50e702011-10-18 21:21:00 +02007669static PyObject *
7670encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007671 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007672 const char *errors)
7673{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007674 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007675 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007676 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007677 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007678
Victor Stinner29dacf22015-01-26 16:41:32 +01007679 if (!PyUnicode_Check(unicode)) {
7680 PyErr_BadArgument();
7681 return NULL;
7682 }
7683
Benjamin Petersonbac79492012-01-14 13:34:47 -05007684 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007685 return NULL;
7686 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007687
Victor Stinner3a50e702011-10-18 21:21:00 +02007688 if (code_page < 0) {
7689 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7690 return NULL;
7691 }
7692
Martin v. Löwis3d325192011-11-04 18:23:06 +01007693 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007694 return PyBytes_FromStringAndSize(NULL, 0);
7695
Victor Stinner7581cef2011-11-03 22:32:33 +01007696 offset = 0;
7697 do
7698 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007699#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007700 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007701 chunks. */
7702 if (len > INT_MAX/2) {
7703 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007704 done = 0;
7705 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007706 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007707#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007708 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007709 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007710 done = 1;
7711 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007712
Victor Stinner76a31a62011-11-04 00:05:13 +01007713 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007714 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007715 errors);
7716 if (ret == -2)
7717 ret = encode_code_page_errors(code_page, &outbytes,
7718 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007719 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007720 if (ret < 0) {
7721 Py_XDECREF(outbytes);
7722 return NULL;
7723 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007724
Victor Stinner7581cef2011-11-03 22:32:33 +01007725 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007726 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007727 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007728
Victor Stinner3a50e702011-10-18 21:21:00 +02007729 return outbytes;
7730}
7731
7732PyObject *
7733PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7734 Py_ssize_t size,
7735 const char *errors)
7736{
Victor Stinner7581cef2011-11-03 22:32:33 +01007737 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007738 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007739 if (unicode == NULL)
7740 return NULL;
7741 res = encode_code_page(CP_ACP, unicode, errors);
7742 Py_DECREF(unicode);
7743 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007744}
7745
7746PyObject *
7747PyUnicode_EncodeCodePage(int code_page,
7748 PyObject *unicode,
7749 const char *errors)
7750{
Victor Stinner7581cef2011-11-03 22:32:33 +01007751 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007752}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007753
Alexander Belopolsky40018472011-02-26 01:02:56 +00007754PyObject *
7755PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007756{
Victor Stinner7581cef2011-11-03 22:32:33 +01007757 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007758}
7759
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007760#undef NEED_RETRY
7761
Steve Dowercc16be82016-09-08 10:35:16 -07007762#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007763
Guido van Rossumd57fd912000-03-10 22:53:23 +00007764/* --- Character Mapping Codec -------------------------------------------- */
7765
Victor Stinnerfb161b12013-04-18 01:44:27 +02007766static int
7767charmap_decode_string(const char *s,
7768 Py_ssize_t size,
7769 PyObject *mapping,
7770 const char *errors,
7771 _PyUnicodeWriter *writer)
7772{
7773 const char *starts = s;
7774 const char *e;
7775 Py_ssize_t startinpos, endinpos;
7776 PyObject *errorHandler = NULL, *exc = NULL;
7777 Py_ssize_t maplen;
7778 enum PyUnicode_Kind mapkind;
7779 void *mapdata;
7780 Py_UCS4 x;
7781 unsigned char ch;
7782
7783 if (PyUnicode_READY(mapping) == -1)
7784 return -1;
7785
7786 maplen = PyUnicode_GET_LENGTH(mapping);
7787 mapdata = PyUnicode_DATA(mapping);
7788 mapkind = PyUnicode_KIND(mapping);
7789
7790 e = s + size;
7791
7792 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7793 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7794 * is disabled in encoding aliases, latin1 is preferred because
7795 * its implementation is faster. */
7796 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7797 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7798 Py_UCS4 maxchar = writer->maxchar;
7799
7800 assert (writer->kind == PyUnicode_1BYTE_KIND);
7801 while (s < e) {
7802 ch = *s;
7803 x = mapdata_ucs1[ch];
7804 if (x > maxchar) {
7805 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7806 goto onError;
7807 maxchar = writer->maxchar;
7808 outdata = (Py_UCS1 *)writer->data;
7809 }
7810 outdata[writer->pos] = x;
7811 writer->pos++;
7812 ++s;
7813 }
7814 return 0;
7815 }
7816
7817 while (s < e) {
7818 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7819 enum PyUnicode_Kind outkind = writer->kind;
7820 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7821 if (outkind == PyUnicode_1BYTE_KIND) {
7822 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7823 Py_UCS4 maxchar = writer->maxchar;
7824 while (s < e) {
7825 ch = *s;
7826 x = mapdata_ucs2[ch];
7827 if (x > maxchar)
7828 goto Error;
7829 outdata[writer->pos] = x;
7830 writer->pos++;
7831 ++s;
7832 }
7833 break;
7834 }
7835 else if (outkind == PyUnicode_2BYTE_KIND) {
7836 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7837 while (s < e) {
7838 ch = *s;
7839 x = mapdata_ucs2[ch];
7840 if (x == 0xFFFE)
7841 goto Error;
7842 outdata[writer->pos] = x;
7843 writer->pos++;
7844 ++s;
7845 }
7846 break;
7847 }
7848 }
7849 ch = *s;
7850
7851 if (ch < maplen)
7852 x = PyUnicode_READ(mapkind, mapdata, ch);
7853 else
7854 x = 0xfffe; /* invalid value */
7855Error:
7856 if (x == 0xfffe)
7857 {
7858 /* undefined mapping */
7859 startinpos = s-starts;
7860 endinpos = startinpos+1;
7861 if (unicode_decode_call_errorhandler_writer(
7862 errors, &errorHandler,
7863 "charmap", "character maps to <undefined>",
7864 &starts, &e, &startinpos, &endinpos, &exc, &s,
7865 writer)) {
7866 goto onError;
7867 }
7868 continue;
7869 }
7870
7871 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7872 goto onError;
7873 ++s;
7874 }
7875 Py_XDECREF(errorHandler);
7876 Py_XDECREF(exc);
7877 return 0;
7878
7879onError:
7880 Py_XDECREF(errorHandler);
7881 Py_XDECREF(exc);
7882 return -1;
7883}
7884
7885static int
7886charmap_decode_mapping(const char *s,
7887 Py_ssize_t size,
7888 PyObject *mapping,
7889 const char *errors,
7890 _PyUnicodeWriter *writer)
7891{
7892 const char *starts = s;
7893 const char *e;
7894 Py_ssize_t startinpos, endinpos;
7895 PyObject *errorHandler = NULL, *exc = NULL;
7896 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007897 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007898
7899 e = s + size;
7900
7901 while (s < e) {
7902 ch = *s;
7903
7904 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7905 key = PyLong_FromLong((long)ch);
7906 if (key == NULL)
7907 goto onError;
7908
7909 item = PyObject_GetItem(mapping, key);
7910 Py_DECREF(key);
7911 if (item == NULL) {
7912 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7913 /* No mapping found means: mapping is undefined. */
7914 PyErr_Clear();
7915 goto Undefined;
7916 } else
7917 goto onError;
7918 }
7919
7920 /* Apply mapping */
7921 if (item == Py_None)
7922 goto Undefined;
7923 if (PyLong_Check(item)) {
7924 long value = PyLong_AS_LONG(item);
7925 if (value == 0xFFFE)
7926 goto Undefined;
7927 if (value < 0 || value > MAX_UNICODE) {
7928 PyErr_Format(PyExc_TypeError,
7929 "character mapping must be in range(0x%lx)",
7930 (unsigned long)MAX_UNICODE + 1);
7931 goto onError;
7932 }
7933
7934 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7935 goto onError;
7936 }
7937 else if (PyUnicode_Check(item)) {
7938 if (PyUnicode_READY(item) == -1)
7939 goto onError;
7940 if (PyUnicode_GET_LENGTH(item) == 1) {
7941 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7942 if (value == 0xFFFE)
7943 goto Undefined;
7944 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7945 goto onError;
7946 }
7947 else {
7948 writer->overallocate = 1;
7949 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7950 goto onError;
7951 }
7952 }
7953 else {
7954 /* wrong return value */
7955 PyErr_SetString(PyExc_TypeError,
7956 "character mapping must return integer, None or str");
7957 goto onError;
7958 }
7959 Py_CLEAR(item);
7960 ++s;
7961 continue;
7962
7963Undefined:
7964 /* undefined mapping */
7965 Py_CLEAR(item);
7966 startinpos = s-starts;
7967 endinpos = startinpos+1;
7968 if (unicode_decode_call_errorhandler_writer(
7969 errors, &errorHandler,
7970 "charmap", "character maps to <undefined>",
7971 &starts, &e, &startinpos, &endinpos, &exc, &s,
7972 writer)) {
7973 goto onError;
7974 }
7975 }
7976 Py_XDECREF(errorHandler);
7977 Py_XDECREF(exc);
7978 return 0;
7979
7980onError:
7981 Py_XDECREF(item);
7982 Py_XDECREF(errorHandler);
7983 Py_XDECREF(exc);
7984 return -1;
7985}
7986
Alexander Belopolsky40018472011-02-26 01:02:56 +00007987PyObject *
7988PyUnicode_DecodeCharmap(const char *s,
7989 Py_ssize_t size,
7990 PyObject *mapping,
7991 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007992{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007993 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007994
Guido van Rossumd57fd912000-03-10 22:53:23 +00007995 /* Default to Latin-1 */
7996 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007998
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008000 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008001 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008002 writer.min_length = size;
8003 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008004 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008005
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008006 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008007 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8008 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008009 }
8010 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008011 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8012 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008013 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008014 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008015
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008017 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008018 return NULL;
8019}
8020
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008021/* Charmap encoding: the lookup table */
8022
Alexander Belopolsky40018472011-02-26 01:02:56 +00008023struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 PyObject_HEAD
8025 unsigned char level1[32];
8026 int count2, count3;
8027 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028};
8029
8030static PyObject*
8031encoding_map_size(PyObject *obj, PyObject* args)
8032{
8033 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008034 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008036}
8037
8038static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008039 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 PyDoc_STR("Return the size (in bytes) of this object") },
8041 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008042};
8043
8044static void
8045encoding_map_dealloc(PyObject* o)
8046{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008047 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008048}
8049
8050static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008051 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 "EncodingMap", /*tp_name*/
8053 sizeof(struct encoding_map), /*tp_basicsize*/
8054 0, /*tp_itemsize*/
8055 /* methods */
8056 encoding_map_dealloc, /*tp_dealloc*/
8057 0, /*tp_print*/
8058 0, /*tp_getattr*/
8059 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008060 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 0, /*tp_repr*/
8062 0, /*tp_as_number*/
8063 0, /*tp_as_sequence*/
8064 0, /*tp_as_mapping*/
8065 0, /*tp_hash*/
8066 0, /*tp_call*/
8067 0, /*tp_str*/
8068 0, /*tp_getattro*/
8069 0, /*tp_setattro*/
8070 0, /*tp_as_buffer*/
8071 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8072 0, /*tp_doc*/
8073 0, /*tp_traverse*/
8074 0, /*tp_clear*/
8075 0, /*tp_richcompare*/
8076 0, /*tp_weaklistoffset*/
8077 0, /*tp_iter*/
8078 0, /*tp_iternext*/
8079 encoding_map_methods, /*tp_methods*/
8080 0, /*tp_members*/
8081 0, /*tp_getset*/
8082 0, /*tp_base*/
8083 0, /*tp_dict*/
8084 0, /*tp_descr_get*/
8085 0, /*tp_descr_set*/
8086 0, /*tp_dictoffset*/
8087 0, /*tp_init*/
8088 0, /*tp_alloc*/
8089 0, /*tp_new*/
8090 0, /*tp_free*/
8091 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092};
8093
8094PyObject*
8095PyUnicode_BuildEncodingMap(PyObject* string)
8096{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008097 PyObject *result;
8098 struct encoding_map *mresult;
8099 int i;
8100 int need_dict = 0;
8101 unsigned char level1[32];
8102 unsigned char level2[512];
8103 unsigned char *mlevel1, *mlevel2, *mlevel3;
8104 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008105 int kind;
8106 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008107 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008108 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008109
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008110 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111 PyErr_BadArgument();
8112 return NULL;
8113 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008114 kind = PyUnicode_KIND(string);
8115 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008116 length = PyUnicode_GET_LENGTH(string);
8117 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008118 memset(level1, 0xFF, sizeof level1);
8119 memset(level2, 0xFF, sizeof level2);
8120
8121 /* If there isn't a one-to-one mapping of NULL to \0,
8122 or if there are non-BMP characters, we need to use
8123 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008124 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008125 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008126 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008127 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008128 ch = PyUnicode_READ(kind, data, i);
8129 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 need_dict = 1;
8131 break;
8132 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008133 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 /* unmapped character */
8135 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008136 l1 = ch >> 11;
8137 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008138 if (level1[l1] == 0xFF)
8139 level1[l1] = count2++;
8140 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008141 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008142 }
8143
8144 if (count2 >= 0xFF || count3 >= 0xFF)
8145 need_dict = 1;
8146
8147 if (need_dict) {
8148 PyObject *result = PyDict_New();
8149 PyObject *key, *value;
8150 if (!result)
8151 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008152 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008153 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008154 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008155 if (!key || !value)
8156 goto failed1;
8157 if (PyDict_SetItem(result, key, value) == -1)
8158 goto failed1;
8159 Py_DECREF(key);
8160 Py_DECREF(value);
8161 }
8162 return result;
8163 failed1:
8164 Py_XDECREF(key);
8165 Py_XDECREF(value);
8166 Py_DECREF(result);
8167 return NULL;
8168 }
8169
8170 /* Create a three-level trie */
8171 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8172 16*count2 + 128*count3 - 1);
8173 if (!result)
8174 return PyErr_NoMemory();
8175 PyObject_Init(result, &EncodingMapType);
8176 mresult = (struct encoding_map*)result;
8177 mresult->count2 = count2;
8178 mresult->count3 = count3;
8179 mlevel1 = mresult->level1;
8180 mlevel2 = mresult->level23;
8181 mlevel3 = mresult->level23 + 16*count2;
8182 memcpy(mlevel1, level1, 32);
8183 memset(mlevel2, 0xFF, 16*count2);
8184 memset(mlevel3, 0, 128*count3);
8185 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008186 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008188 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8189 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190 /* unmapped character */
8191 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008192 o1 = ch>>11;
8193 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008194 i2 = 16*mlevel1[o1] + o2;
8195 if (mlevel2[i2] == 0xFF)
8196 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008197 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008198 i3 = 128*mlevel2[i2] + o3;
8199 mlevel3[i3] = i;
8200 }
8201 return result;
8202}
8203
8204static int
Victor Stinner22168992011-11-20 17:09:18 +01008205encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008206{
8207 struct encoding_map *map = (struct encoding_map*)mapping;
8208 int l1 = c>>11;
8209 int l2 = (c>>7) & 0xF;
8210 int l3 = c & 0x7F;
8211 int i;
8212
Victor Stinner22168992011-11-20 17:09:18 +01008213 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008215 if (c == 0)
8216 return 0;
8217 /* level 1*/
8218 i = map->level1[l1];
8219 if (i == 0xFF) {
8220 return -1;
8221 }
8222 /* level 2*/
8223 i = map->level23[16*i+l2];
8224 if (i == 0xFF) {
8225 return -1;
8226 }
8227 /* level 3 */
8228 i = map->level23[16*map->count2 + 128*i + l3];
8229 if (i == 0) {
8230 return -1;
8231 }
8232 return i;
8233}
8234
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235/* Lookup the character ch in the mapping. If the character
8236 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008237 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008238static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008239charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240{
Christian Heimes217cfd12007-12-02 14:31:20 +00008241 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242 PyObject *x;
8243
8244 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246 x = PyObject_GetItem(mapping, w);
8247 Py_DECREF(w);
8248 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8250 /* No mapping found means: mapping is undefined. */
8251 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008252 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 } else
8254 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008256 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008258 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008259 long value = PyLong_AS_LONG(x);
8260 if (value < 0 || value > 255) {
8261 PyErr_SetString(PyExc_TypeError,
8262 "character mapping must be in range(256)");
8263 Py_DECREF(x);
8264 return NULL;
8265 }
8266 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008267 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008268 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008270 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 /* wrong return value */
8272 PyErr_Format(PyExc_TypeError,
8273 "character mapping must return integer, bytes or None, not %.400s",
8274 x->ob_type->tp_name);
8275 Py_DECREF(x);
8276 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008277 }
8278}
8279
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008280static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008281charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008282{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008283 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8284 /* exponentially overallocate to minimize reallocations */
8285 if (requiredsize < 2*outsize)
8286 requiredsize = 2*outsize;
8287 if (_PyBytes_Resize(outobj, requiredsize))
8288 return -1;
8289 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008290}
8291
Benjamin Peterson14339b62009-01-31 16:36:08 +00008292typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008294} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008296 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008297 space is available. Return a new reference to the object that
8298 was put in the output buffer, or Py_None, if the mapping was undefined
8299 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008300 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008301static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008302charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008303 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008305 PyObject *rep;
8306 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008307 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308
Christian Heimes90aa7642007-12-19 02:45:37 +00008309 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008310 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008312 if (res == -1)
8313 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 if (outsize<requiredsize)
8315 if (charmapencode_resize(outobj, outpos, requiredsize))
8316 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008317 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 outstart[(*outpos)++] = (char)res;
8319 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008320 }
8321
8322 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008324 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008325 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 Py_DECREF(rep);
8327 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008328 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008329 if (PyLong_Check(rep)) {
8330 Py_ssize_t requiredsize = *outpos+1;
8331 if (outsize<requiredsize)
8332 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8333 Py_DECREF(rep);
8334 return enc_EXCEPTION;
8335 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008336 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008338 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008339 else {
8340 const char *repchars = PyBytes_AS_STRING(rep);
8341 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8342 Py_ssize_t requiredsize = *outpos+repsize;
8343 if (outsize<requiredsize)
8344 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8345 Py_DECREF(rep);
8346 return enc_EXCEPTION;
8347 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008348 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008349 memcpy(outstart + *outpos, repchars, repsize);
8350 *outpos += repsize;
8351 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008353 Py_DECREF(rep);
8354 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355}
8356
8357/* handle an error in PyUnicode_EncodeCharmap
8358 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008359static int
8360charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008361 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008363 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008364 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365{
8366 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008367 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008368 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008369 enum PyUnicode_Kind kind;
8370 void *data;
8371 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008372 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008373 Py_ssize_t collstartpos = *inpos;
8374 Py_ssize_t collendpos = *inpos+1;
8375 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008376 const char *encoding = "charmap";
8377 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008378 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008379 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008380 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381
Benjamin Petersonbac79492012-01-14 13:34:47 -05008382 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008383 return -1;
8384 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008385 /* find all unencodable characters */
8386 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008387 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008388 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008389 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008390 val = encoding_map_lookup(ch, mapping);
8391 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 break;
8393 ++collendpos;
8394 continue;
8395 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008396
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008397 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8398 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008399 if (rep==NULL)
8400 return -1;
8401 else if (rep!=Py_None) {
8402 Py_DECREF(rep);
8403 break;
8404 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008405 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 }
8408 /* cache callback name lookup
8409 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008410 if (*error_handler == _Py_ERROR_UNKNOWN)
8411 *error_handler = get_error_handler(errors);
8412
8413 switch (*error_handler) {
8414 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008415 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008416 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008417
8418 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008419 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 x = charmapencode_output('?', mapping, res, respos);
8421 if (x==enc_EXCEPTION) {
8422 return -1;
8423 }
8424 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008425 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 return -1;
8427 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008428 }
8429 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008430 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008431 *inpos = collendpos;
8432 break;
Victor Stinner50149202015-09-22 00:26:54 +02008433
8434 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008435 /* generate replacement (temporarily (mis)uses p) */
8436 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 char buffer[2+29+1+1];
8438 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008439 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 for (cp = buffer; *cp; ++cp) {
8441 x = charmapencode_output(*cp, mapping, res, respos);
8442 if (x==enc_EXCEPTION)
8443 return -1;
8444 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008445 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 return -1;
8447 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008448 }
8449 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008450 *inpos = collendpos;
8451 break;
Victor Stinner50149202015-09-22 00:26:54 +02008452
Benjamin Peterson14339b62009-01-31 16:36:08 +00008453 default:
Victor Stinner50149202015-09-22 00:26:54 +02008454 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008455 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008457 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008459 if (PyBytes_Check(repunicode)) {
8460 /* Directly copy bytes result to output. */
8461 Py_ssize_t outsize = PyBytes_Size(*res);
8462 Py_ssize_t requiredsize;
8463 repsize = PyBytes_Size(repunicode);
8464 requiredsize = *respos + repsize;
8465 if (requiredsize > outsize)
8466 /* Make room for all additional bytes. */
8467 if (charmapencode_resize(res, respos, requiredsize)) {
8468 Py_DECREF(repunicode);
8469 return -1;
8470 }
8471 memcpy(PyBytes_AsString(*res) + *respos,
8472 PyBytes_AsString(repunicode), repsize);
8473 *respos += repsize;
8474 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008475 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008476 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008477 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008478 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008479 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008480 Py_DECREF(repunicode);
8481 return -1;
8482 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008483 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008484 data = PyUnicode_DATA(repunicode);
8485 kind = PyUnicode_KIND(repunicode);
8486 for (index = 0; index < repsize; index++) {
8487 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8488 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008490 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 return -1;
8492 }
8493 else if (x==enc_FAILED) {
8494 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008495 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 return -1;
8497 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008498 }
8499 *inpos = newpos;
8500 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 }
8502 return 0;
8503}
8504
Alexander Belopolsky40018472011-02-26 01:02:56 +00008505PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008506_PyUnicode_EncodeCharmap(PyObject *unicode,
8507 PyObject *mapping,
8508 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008509{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 /* output object */
8511 PyObject *res = NULL;
8512 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008513 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008516 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008517 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008519 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008520 void *data;
8521 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008522
Benjamin Petersonbac79492012-01-14 13:34:47 -05008523 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008524 return NULL;
8525 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008526 data = PyUnicode_DATA(unicode);
8527 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008528
Guido van Rossumd57fd912000-03-10 22:53:23 +00008529 /* Default to Latin-1 */
8530 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008531 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008532
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533 /* allocate enough for a simple encoding without
8534 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008535 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008536 if (res == NULL)
8537 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008538 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008540
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008542 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008544 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 if (x==enc_EXCEPTION) /* error */
8546 goto onError;
8547 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008548 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008549 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008550 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 &res, &respos)) {
8552 goto onError;
8553 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008554 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008555 else
8556 /* done with this character => adjust input position */
8557 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008558 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008561 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008562 if (_PyBytes_Resize(&res, respos) < 0)
8563 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008564
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008566 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008567 return res;
8568
Benjamin Peterson29060642009-01-31 22:14:21 +00008569 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570 Py_XDECREF(res);
8571 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008572 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008573 return NULL;
8574}
8575
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008576/* Deprecated */
8577PyObject *
8578PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8579 Py_ssize_t size,
8580 PyObject *mapping,
8581 const char *errors)
8582{
8583 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008584 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008585 if (unicode == NULL)
8586 return NULL;
8587 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8588 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008589 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008590}
8591
Alexander Belopolsky40018472011-02-26 01:02:56 +00008592PyObject *
8593PyUnicode_AsCharmapString(PyObject *unicode,
8594 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008595{
8596 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 PyErr_BadArgument();
8598 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008599 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008600 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008601}
8602
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008603/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008604static void
8605make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008607 Py_ssize_t startpos, Py_ssize_t endpos,
8608 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008609{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 *exceptionObject = _PyUnicodeTranslateError_Create(
8612 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008613 }
8614 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8616 goto onError;
8617 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8618 goto onError;
8619 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8620 goto onError;
8621 return;
8622 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008623 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008624 }
8625}
8626
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627/* error handling callback helper:
8628 build arguments, call the callback and check the arguments,
8629 put the result into newpos and return the replacement string, which
8630 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008631static PyObject *
8632unicode_translate_call_errorhandler(const char *errors,
8633 PyObject **errorHandler,
8634 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008636 Py_ssize_t startpos, Py_ssize_t endpos,
8637 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008639 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008641 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642 PyObject *restuple;
8643 PyObject *resunicode;
8644
8645 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008647 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 }
8650
8651 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008653 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008656 restuple = PyObject_CallFunctionObjArgs(
8657 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008658 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008659 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008661 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 Py_DECREF(restuple);
8663 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008665 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008666 &resunicode, &i_newpos)) {
8667 Py_DECREF(restuple);
8668 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008670 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008672 else
8673 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008675 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 Py_DECREF(restuple);
8677 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008678 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679 Py_INCREF(resunicode);
8680 Py_DECREF(restuple);
8681 return resunicode;
8682}
8683
8684/* Lookup the character ch in the mapping and put the result in result,
8685 which must be decrefed by the caller.
8686 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008687static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008689{
Christian Heimes217cfd12007-12-02 14:31:20 +00008690 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 PyObject *x;
8692
8693 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008695 x = PyObject_GetItem(mapping, w);
8696 Py_DECREF(w);
8697 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8699 /* No mapping found means: use 1:1 mapping. */
8700 PyErr_Clear();
8701 *result = NULL;
8702 return 0;
8703 } else
8704 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008705 }
8706 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 *result = x;
8708 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008709 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008710 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008712 if (value < 0 || value > MAX_UNICODE) {
8713 PyErr_Format(PyExc_ValueError,
8714 "character mapping must be in range(0x%x)",
8715 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 Py_DECREF(x);
8717 return -1;
8718 }
8719 *result = x;
8720 return 0;
8721 }
8722 else if (PyUnicode_Check(x)) {
8723 *result = x;
8724 return 0;
8725 }
8726 else {
8727 /* wrong return value */
8728 PyErr_SetString(PyExc_TypeError,
8729 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008730 Py_DECREF(x);
8731 return -1;
8732 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008733}
Victor Stinner1194ea02014-04-04 19:37:40 +02008734
8735/* lookup the character, write the result into the writer.
8736 Return 1 if the result was written into the writer, return 0 if the mapping
8737 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008738static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008739charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8740 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008741{
Victor Stinner1194ea02014-04-04 19:37:40 +02008742 PyObject *item;
8743
8744 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008745 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008746
8747 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008749 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008751 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008752 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008753 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008754
8755 if (item == Py_None) {
8756 Py_DECREF(item);
8757 return 0;
8758 }
8759
8760 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008761 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8762 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8763 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008764 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8765 Py_DECREF(item);
8766 return -1;
8767 }
8768 Py_DECREF(item);
8769 return 1;
8770 }
8771
8772 if (!PyUnicode_Check(item)) {
8773 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008775 }
8776
8777 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8778 Py_DECREF(item);
8779 return -1;
8780 }
8781
8782 Py_DECREF(item);
8783 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008784}
8785
Victor Stinner89a76ab2014-04-05 11:44:04 +02008786static int
8787unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8788 Py_UCS1 *translate)
8789{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008790 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008791 int ret = 0;
8792
Victor Stinner89a76ab2014-04-05 11:44:04 +02008793 if (charmaptranslate_lookup(ch, mapping, &item)) {
8794 return -1;
8795 }
8796
8797 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008798 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008799 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008800 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008801 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008802 /* not found => default to 1:1 mapping */
8803 translate[ch] = ch;
8804 return 1;
8805 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008806 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008807 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008808 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8809 used it */
8810 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008811 /* invalid character or character outside ASCII:
8812 skip the fast translate */
8813 goto exit;
8814 }
8815 translate[ch] = (Py_UCS1)replace;
8816 }
8817 else if (PyUnicode_Check(item)) {
8818 Py_UCS4 replace;
8819
8820 if (PyUnicode_READY(item) == -1) {
8821 Py_DECREF(item);
8822 return -1;
8823 }
8824 if (PyUnicode_GET_LENGTH(item) != 1)
8825 goto exit;
8826
8827 replace = PyUnicode_READ_CHAR(item, 0);
8828 if (replace > 127)
8829 goto exit;
8830 translate[ch] = (Py_UCS1)replace;
8831 }
8832 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008833 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008834 goto exit;
8835 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008836 ret = 1;
8837
Benjamin Peterson1365de72014-04-07 20:15:41 -04008838 exit:
8839 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008840 return ret;
8841}
8842
8843/* Fast path for ascii => ascii translation. Return 1 if the whole string
8844 was translated into writer, return 0 if the input string was partially
8845 translated into writer, raise an exception and return -1 on error. */
8846static int
8847unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008848 _PyUnicodeWriter *writer, int ignore,
8849 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008850{
Victor Stinner872b2912014-04-05 14:27:07 +02008851 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008852 Py_ssize_t len;
8853 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008854 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008855
Victor Stinner89a76ab2014-04-05 11:44:04 +02008856 len = PyUnicode_GET_LENGTH(input);
8857
Victor Stinner872b2912014-04-05 14:27:07 +02008858 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859
8860 in = PyUnicode_1BYTE_DATA(input);
8861 end = in + len;
8862
8863 assert(PyUnicode_IS_ASCII(writer->buffer));
8864 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8865 out = PyUnicode_1BYTE_DATA(writer->buffer);
8866
Victor Stinner872b2912014-04-05 14:27:07 +02008867 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008868 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008869 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008870 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008871 int translate = unicode_fast_translate_lookup(mapping, ch,
8872 ascii_table);
8873 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008874 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008875 if (translate == 0)
8876 goto exit;
8877 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878 }
Victor Stinner872b2912014-04-05 14:27:07 +02008879 if (ch2 == 0xfe) {
8880 if (ignore)
8881 continue;
8882 goto exit;
8883 }
8884 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008885 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008886 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008887 }
Victor Stinner872b2912014-04-05 14:27:07 +02008888 res = 1;
8889
8890exit:
8891 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008892 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008893 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008894}
8895
Victor Stinner3222da22015-10-01 22:07:32 +02008896static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897_PyUnicode_TranslateCharmap(PyObject *input,
8898 PyObject *mapping,
8899 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008902 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008903 Py_ssize_t size, i;
8904 int kind;
8905 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008906 _PyUnicodeWriter writer;
8907 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008908 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008909 PyObject *errorHandler = NULL;
8910 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008911 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008912 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008913
Guido van Rossumd57fd912000-03-10 22:53:23 +00008914 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008915 PyErr_BadArgument();
8916 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008917 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008919 if (PyUnicode_READY(input) == -1)
8920 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008921 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008922 kind = PyUnicode_KIND(input);
8923 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008925 if (size == 0)
8926 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008927
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008928 /* allocate enough for a simple 1:1 translation without
8929 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008930 _PyUnicodeWriter_Init(&writer);
8931 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008932 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008933
Victor Stinner872b2912014-04-05 14:27:07 +02008934 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8935
Victor Stinner33798672016-03-01 21:59:58 +01008936 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008937 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008938 if (PyUnicode_IS_ASCII(input)) {
8939 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8940 if (res < 0) {
8941 _PyUnicodeWriter_Dealloc(&writer);
8942 return NULL;
8943 }
8944 if (res == 1)
8945 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008946 }
Victor Stinner33798672016-03-01 21:59:58 +01008947 else {
8948 i = 0;
8949 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008950
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008952 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008953 int translate;
8954 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8955 Py_ssize_t newpos;
8956 /* startpos for collecting untranslatable chars */
8957 Py_ssize_t collstart;
8958 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008959 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008960
Victor Stinner1194ea02014-04-04 19:37:40 +02008961 ch = PyUnicode_READ(kind, data, i);
8962 translate = charmaptranslate_output(ch, mapping, &writer);
8963 if (translate < 0)
8964 goto onError;
8965
8966 if (translate != 0) {
8967 /* it worked => adjust input pointer */
8968 ++i;
8969 continue;
8970 }
8971
8972 /* untranslatable character */
8973 collstart = i;
8974 collend = i+1;
8975
8976 /* find all untranslatable characters */
8977 while (collend < size) {
8978 PyObject *x;
8979 ch = PyUnicode_READ(kind, data, collend);
8980 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008981 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008982 Py_XDECREF(x);
8983 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008984 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008985 ++collend;
8986 }
8987
8988 if (ignore) {
8989 i = collend;
8990 }
8991 else {
8992 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8993 reason, input, &exc,
8994 collstart, collend, &newpos);
8995 if (repunicode == NULL)
8996 goto onError;
8997 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008998 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008999 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009000 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009001 Py_DECREF(repunicode);
9002 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009003 }
9004 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009005 Py_XDECREF(exc);
9006 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009007 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009008
Benjamin Peterson29060642009-01-31 22:14:21 +00009009 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009010 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009011 Py_XDECREF(exc);
9012 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013 return NULL;
9014}
9015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016/* Deprecated. Use PyUnicode_Translate instead. */
9017PyObject *
9018PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9019 Py_ssize_t size,
9020 PyObject *mapping,
9021 const char *errors)
9022{
Christian Heimes5f520f42012-09-11 14:03:25 +02009023 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009024 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009025 if (!unicode)
9026 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009027 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9028 Py_DECREF(unicode);
9029 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009030}
9031
Alexander Belopolsky40018472011-02-26 01:02:56 +00009032PyObject *
9033PyUnicode_Translate(PyObject *str,
9034 PyObject *mapping,
9035 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009037 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009038 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009039 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009040}
Tim Petersced69f82003-09-16 20:30:58 +00009041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042PyObject *
9043_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9044{
9045 if (!PyUnicode_Check(unicode)) {
9046 PyErr_BadInternalCall();
9047 return NULL;
9048 }
9049 if (PyUnicode_READY(unicode) == -1)
9050 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009051 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009052 /* If the string is already ASCII, just return the same string */
9053 Py_INCREF(unicode);
9054 return unicode;
9055 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009056
9057 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9058 PyObject *result = PyUnicode_New(len, 127);
9059 if (result == NULL) {
9060 return NULL;
9061 }
9062
9063 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9064 int kind = PyUnicode_KIND(unicode);
9065 const void *data = PyUnicode_DATA(unicode);
9066 Py_ssize_t i;
9067 for (i = 0; i < len; ++i) {
9068 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9069 if (ch < 127) {
9070 out[i] = ch;
9071 }
9072 else if (Py_UNICODE_ISSPACE(ch)) {
9073 out[i] = ' ';
9074 }
9075 else {
9076 int decimal = Py_UNICODE_TODECIMAL(ch);
9077 if (decimal < 0) {
9078 out[i] = '?';
Miss Islington (bot)c7214722018-07-13 20:58:12 -07009079 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009080 _PyUnicode_LENGTH(result) = i + 1;
9081 break;
9082 }
9083 out[i] = '0' + decimal;
9084 }
9085 }
9086
Miss Islington (bot)c7214722018-07-13 20:58:12 -07009087 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009088 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089}
9090
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009091PyObject *
9092PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9093 Py_ssize_t length)
9094{
Victor Stinnerf0124502011-11-21 23:12:56 +01009095 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009096 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009097 Py_UCS4 maxchar;
9098 enum PyUnicode_Kind kind;
9099 void *data;
9100
Victor Stinner99d7ad02012-02-22 13:37:39 +01009101 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009102 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009103 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009104 if (ch > 127) {
9105 int decimal = Py_UNICODE_TODECIMAL(ch);
9106 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009107 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009108 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009109 }
9110 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009111
9112 /* Copy to a new string */
9113 decimal = PyUnicode_New(length, maxchar);
9114 if (decimal == NULL)
9115 return decimal;
9116 kind = PyUnicode_KIND(decimal);
9117 data = PyUnicode_DATA(decimal);
9118 /* Iterate over code points */
9119 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009120 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009121 if (ch > 127) {
9122 int decimal = Py_UNICODE_TODECIMAL(ch);
9123 if (decimal >= 0)
9124 ch = '0' + decimal;
9125 }
9126 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009127 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009128 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009129}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009130/* --- Decimal Encoder ---------------------------------------------------- */
9131
Alexander Belopolsky40018472011-02-26 01:02:56 +00009132int
9133PyUnicode_EncodeDecimal(Py_UNICODE *s,
9134 Py_ssize_t length,
9135 char *output,
9136 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009137{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009138 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009139 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009140 enum PyUnicode_Kind kind;
9141 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009142
9143 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009144 PyErr_BadArgument();
9145 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009146 }
9147
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009148 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009149 if (unicode == NULL)
9150 return -1;
9151
Victor Stinner42bf7752011-11-21 22:52:58 +01009152 kind = PyUnicode_KIND(unicode);
9153 data = PyUnicode_DATA(unicode);
9154
Victor Stinnerb84d7232011-11-22 01:50:07 +01009155 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009156 PyObject *exc;
9157 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009158 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009159 Py_ssize_t startpos;
9160
9161 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009162
Benjamin Peterson29060642009-01-31 22:14:21 +00009163 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009164 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009165 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009166 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009167 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009168 decimal = Py_UNICODE_TODECIMAL(ch);
9169 if (decimal >= 0) {
9170 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009171 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009172 continue;
9173 }
9174 if (0 < ch && ch < 256) {
9175 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009176 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009177 continue;
9178 }
Victor Stinner6345be92011-11-25 20:09:01 +01009179
Victor Stinner42bf7752011-11-21 22:52:58 +01009180 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009181 exc = NULL;
9182 raise_encode_exception(&exc, "decimal", unicode,
9183 startpos, startpos+1,
9184 "invalid decimal Unicode string");
9185 Py_XDECREF(exc);
9186 Py_DECREF(unicode);
9187 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009188 }
9189 /* 0-terminate the output string */
9190 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009191 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009192 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009193}
9194
Guido van Rossumd57fd912000-03-10 22:53:23 +00009195/* --- Helpers ------------------------------------------------------------ */
9196
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009197/* helper macro to fixup start/end slice values */
9198#define ADJUST_INDICES(start, end, len) \
9199 if (end > len) \
9200 end = len; \
9201 else if (end < 0) { \
9202 end += len; \
9203 if (end < 0) \
9204 end = 0; \
9205 } \
9206 if (start < 0) { \
9207 start += len; \
9208 if (start < 0) \
9209 start = 0; \
9210 }
9211
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009213any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009214 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009215 Py_ssize_t end,
9216 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009217{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009218 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 void *buf1, *buf2;
9220 Py_ssize_t len1, len2, result;
9221
9222 kind1 = PyUnicode_KIND(s1);
9223 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009224 if (kind1 < kind2)
9225 return -1;
9226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009227 len1 = PyUnicode_GET_LENGTH(s1);
9228 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009229 ADJUST_INDICES(start, end, len1);
9230 if (end - start < len2)
9231 return -1;
9232
9233 buf1 = PyUnicode_DATA(s1);
9234 buf2 = PyUnicode_DATA(s2);
9235 if (len2 == 1) {
9236 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9237 result = findchar((const char *)buf1 + kind1*start,
9238 kind1, end - start, ch, direction);
9239 if (result == -1)
9240 return -1;
9241 else
9242 return start + result;
9243 }
9244
9245 if (kind2 != kind1) {
9246 buf2 = _PyUnicode_AsKind(s2, kind1);
9247 if (!buf2)
9248 return -2;
9249 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009250
Victor Stinner794d5672011-10-10 03:21:36 +02009251 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009252 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009253 case PyUnicode_1BYTE_KIND:
9254 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9255 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9256 else
9257 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9258 break;
9259 case PyUnicode_2BYTE_KIND:
9260 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9261 break;
9262 case PyUnicode_4BYTE_KIND:
9263 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9264 break;
9265 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009266 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009267 }
9268 }
9269 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009270 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009271 case PyUnicode_1BYTE_KIND:
9272 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9273 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9274 else
9275 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9276 break;
9277 case PyUnicode_2BYTE_KIND:
9278 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9279 break;
9280 case PyUnicode_4BYTE_KIND:
9281 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9282 break;
9283 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009284 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009285 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009286 }
9287
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009288 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009289 PyMem_Free(buf2);
9290
9291 return result;
9292}
9293
9294Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009295_PyUnicode_InsertThousandsGrouping(
9296 PyObject *unicode, Py_ssize_t index,
9297 Py_ssize_t n_buffer,
9298 void *digits, Py_ssize_t n_digits,
9299 Py_ssize_t min_width,
9300 const char *grouping, PyObject *thousands_sep,
9301 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302{
Victor Stinner41a863c2012-02-24 00:37:51 +01009303 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009304 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009305 Py_ssize_t thousands_sep_len;
9306 Py_ssize_t len;
9307
9308 if (unicode != NULL) {
9309 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009310 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009311 }
9312 else {
9313 kind = PyUnicode_1BYTE_KIND;
9314 data = NULL;
9315 }
9316 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9317 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9318 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9319 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009320 if (thousands_sep_kind < kind) {
9321 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9322 if (!thousands_sep_data)
9323 return -1;
9324 }
9325 else {
9326 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9327 if (!data)
9328 return -1;
9329 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009330 }
9331
Benjamin Petersonead6b532011-12-20 17:23:42 -06009332 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009333 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009334 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009335 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009336 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009337 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009338 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009339 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009340 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009341 (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 Stinner41a863c2012-02-24 00:37:51 +01009344 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009345 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009346 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009347 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009348 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009349 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009350 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009351 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009352 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009353 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009354 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009355 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009356 break;
9357 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009358 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009359 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009360 if (unicode != NULL && thousands_sep_kind != kind) {
9361 if (thousands_sep_kind < kind)
9362 PyMem_Free(thousands_sep_data);
9363 else
9364 PyMem_Free(data);
9365 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009366 if (unicode == NULL) {
9367 *maxchar = 127;
9368 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009369 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009370 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009371 }
9372 }
9373 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009374}
9375
9376
Alexander Belopolsky40018472011-02-26 01:02:56 +00009377Py_ssize_t
9378PyUnicode_Count(PyObject *str,
9379 PyObject *substr,
9380 Py_ssize_t start,
9381 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009383 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009384 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385 void *buf1 = NULL, *buf2 = NULL;
9386 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009387
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009388 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009389 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009390
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009391 kind1 = PyUnicode_KIND(str);
9392 kind2 = PyUnicode_KIND(substr);
9393 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009394 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009395
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009396 len1 = PyUnicode_GET_LENGTH(str);
9397 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009399 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009400 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009401
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009402 buf1 = PyUnicode_DATA(str);
9403 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009404 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009405 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009406 if (!buf2)
9407 goto onError;
9408 }
9409
9410 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009411 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009412 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009413 result = asciilib_count(
9414 ((Py_UCS1*)buf1) + start, end - start,
9415 buf2, len2, PY_SSIZE_T_MAX
9416 );
9417 else
9418 result = ucs1lib_count(
9419 ((Py_UCS1*)buf1) + start, end - start,
9420 buf2, len2, PY_SSIZE_T_MAX
9421 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 break;
9423 case PyUnicode_2BYTE_KIND:
9424 result = ucs2lib_count(
9425 ((Py_UCS2*)buf1) + start, end - start,
9426 buf2, len2, PY_SSIZE_T_MAX
9427 );
9428 break;
9429 case PyUnicode_4BYTE_KIND:
9430 result = ucs4lib_count(
9431 ((Py_UCS4*)buf1) + start, end - start,
9432 buf2, len2, PY_SSIZE_T_MAX
9433 );
9434 break;
9435 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009436 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009438
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009439 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009440 PyMem_Free(buf2);
9441
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009444 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445 PyMem_Free(buf2);
9446 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447}
9448
Alexander Belopolsky40018472011-02-26 01:02:56 +00009449Py_ssize_t
9450PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009451 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009452 Py_ssize_t start,
9453 Py_ssize_t end,
9454 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009455{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009456 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009457 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009458
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009459 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009460}
9461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462Py_ssize_t
9463PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9464 Py_ssize_t start, Py_ssize_t end,
9465 int direction)
9466{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009468 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 if (PyUnicode_READY(str) == -1)
9470 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009471 len = PyUnicode_GET_LENGTH(str);
9472 ADJUST_INDICES(start, end, len);
9473 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009474 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009476 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9477 kind, end-start, ch, direction);
9478 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009480 else
9481 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482}
9483
Alexander Belopolsky40018472011-02-26 01:02:56 +00009484static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009485tailmatch(PyObject *self,
9486 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009487 Py_ssize_t start,
9488 Py_ssize_t end,
9489 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491 int kind_self;
9492 int kind_sub;
9493 void *data_self;
9494 void *data_sub;
9495 Py_ssize_t offset;
9496 Py_ssize_t i;
9497 Py_ssize_t end_sub;
9498
9499 if (PyUnicode_READY(self) == -1 ||
9500 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009501 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9504 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009506 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009507
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009508 if (PyUnicode_GET_LENGTH(substring) == 0)
9509 return 1;
9510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009511 kind_self = PyUnicode_KIND(self);
9512 data_self = PyUnicode_DATA(self);
9513 kind_sub = PyUnicode_KIND(substring);
9514 data_sub = PyUnicode_DATA(substring);
9515 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9516
9517 if (direction > 0)
9518 offset = end;
9519 else
9520 offset = start;
9521
9522 if (PyUnicode_READ(kind_self, data_self, offset) ==
9523 PyUnicode_READ(kind_sub, data_sub, 0) &&
9524 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9525 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9526 /* If both are of the same kind, memcmp is sufficient */
9527 if (kind_self == kind_sub) {
9528 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009529 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009530 data_sub,
9531 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009532 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009533 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009534 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 else {
9536 /* We do not need to compare 0 and len(substring)-1 because
9537 the if statement above ensured already that they are equal
9538 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009539 for (i = 1; i < end_sub; ++i) {
9540 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9541 PyUnicode_READ(kind_sub, data_sub, i))
9542 return 0;
9543 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009544 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546 }
9547
9548 return 0;
9549}
9550
Alexander Belopolsky40018472011-02-26 01:02:56 +00009551Py_ssize_t
9552PyUnicode_Tailmatch(PyObject *str,
9553 PyObject *substr,
9554 Py_ssize_t start,
9555 Py_ssize_t end,
9556 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009557{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009558 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009559 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009560
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009561 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009562}
9563
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009564static PyObject *
9565ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009567 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9568 char *resdata, *data = PyUnicode_DATA(self);
9569 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009570
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009571 res = PyUnicode_New(len, 127);
9572 if (res == NULL)
9573 return NULL;
9574 resdata = PyUnicode_DATA(res);
9575 if (lower)
9576 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009577 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009578 _Py_bytes_upper(resdata, data, len);
9579 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009580}
9581
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009583handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009584{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009585 Py_ssize_t j;
9586 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009587 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009588 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009589
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009590 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9591
9592 where ! is a negation and \p{xxx} is a character with property xxx.
9593 */
9594 for (j = i - 1; j >= 0; j--) {
9595 c = PyUnicode_READ(kind, data, j);
9596 if (!_PyUnicode_IsCaseIgnorable(c))
9597 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009598 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009599 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9600 if (final_sigma) {
9601 for (j = i + 1; j < length; j++) {
9602 c = PyUnicode_READ(kind, data, j);
9603 if (!_PyUnicode_IsCaseIgnorable(c))
9604 break;
9605 }
9606 final_sigma = j == length || !_PyUnicode_IsCased(c);
9607 }
9608 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009609}
9610
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009611static int
9612lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9613 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009614{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009615 /* Obscure special case. */
9616 if (c == 0x3A3) {
9617 mapped[0] = handle_capital_sigma(kind, data, length, i);
9618 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009619 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009620 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621}
9622
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009623static Py_ssize_t
9624do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009626 Py_ssize_t i, k = 0;
9627 int n_res, j;
9628 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009629
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009630 c = PyUnicode_READ(kind, data, 0);
9631 n_res = _PyUnicode_ToUpperFull(c, mapped);
9632 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009633 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009634 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009635 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009636 for (i = 1; i < length; i++) {
9637 c = PyUnicode_READ(kind, data, i);
9638 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9639 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009640 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009641 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009642 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009643 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009644 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645}
9646
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647static Py_ssize_t
9648do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9649 Py_ssize_t i, k = 0;
9650
9651 for (i = 0; i < length; i++) {
9652 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9653 int n_res, j;
9654 if (Py_UNICODE_ISUPPER(c)) {
9655 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9656 }
9657 else if (Py_UNICODE_ISLOWER(c)) {
9658 n_res = _PyUnicode_ToUpperFull(c, mapped);
9659 }
9660 else {
9661 n_res = 1;
9662 mapped[0] = c;
9663 }
9664 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009665 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009666 res[k++] = mapped[j];
9667 }
9668 }
9669 return k;
9670}
9671
9672static Py_ssize_t
9673do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9674 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009675{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009676 Py_ssize_t i, k = 0;
9677
9678 for (i = 0; i < length; i++) {
9679 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9680 int n_res, j;
9681 if (lower)
9682 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9683 else
9684 n_res = _PyUnicode_ToUpperFull(c, mapped);
9685 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009686 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009687 res[k++] = mapped[j];
9688 }
9689 }
9690 return k;
9691}
9692
9693static Py_ssize_t
9694do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9695{
9696 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9697}
9698
9699static Py_ssize_t
9700do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9701{
9702 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9703}
9704
Benjamin Petersone51757f2012-01-12 21:10:29 -05009705static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009706do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9707{
9708 Py_ssize_t i, k = 0;
9709
9710 for (i = 0; i < length; i++) {
9711 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9712 Py_UCS4 mapped[3];
9713 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9714 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009715 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009716 res[k++] = mapped[j];
9717 }
9718 }
9719 return k;
9720}
9721
9722static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009723do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9724{
9725 Py_ssize_t i, k = 0;
9726 int previous_is_cased;
9727
9728 previous_is_cased = 0;
9729 for (i = 0; i < length; i++) {
9730 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9731 Py_UCS4 mapped[3];
9732 int n_res, j;
9733
9734 if (previous_is_cased)
9735 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9736 else
9737 n_res = _PyUnicode_ToTitleFull(c, mapped);
9738
9739 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009740 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009741 res[k++] = mapped[j];
9742 }
9743
9744 previous_is_cased = _PyUnicode_IsCased(c);
9745 }
9746 return k;
9747}
9748
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009749static PyObject *
9750case_operation(PyObject *self,
9751 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9752{
9753 PyObject *res = NULL;
9754 Py_ssize_t length, newlength = 0;
9755 int kind, outkind;
9756 void *data, *outdata;
9757 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9758
Benjamin Petersoneea48462012-01-16 14:28:50 -05009759 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009760
9761 kind = PyUnicode_KIND(self);
9762 data = PyUnicode_DATA(self);
9763 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009764 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009765 PyErr_SetString(PyExc_OverflowError, "string is too long");
9766 return NULL;
9767 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009768 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009769 if (tmp == NULL)
9770 return PyErr_NoMemory();
9771 newlength = perform(kind, data, length, tmp, &maxchar);
9772 res = PyUnicode_New(newlength, maxchar);
9773 if (res == NULL)
9774 goto leave;
9775 tmpend = tmp + newlength;
9776 outdata = PyUnicode_DATA(res);
9777 outkind = PyUnicode_KIND(res);
9778 switch (outkind) {
9779 case PyUnicode_1BYTE_KIND:
9780 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9781 break;
9782 case PyUnicode_2BYTE_KIND:
9783 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9784 break;
9785 case PyUnicode_4BYTE_KIND:
9786 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9787 break;
9788 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009789 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009790 }
9791 leave:
9792 PyMem_FREE(tmp);
9793 return res;
9794}
9795
Tim Peters8ce9f162004-08-27 01:49:32 +00009796PyObject *
9797PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009799 PyObject *res;
9800 PyObject *fseq;
9801 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009802 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009804 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009805 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009806 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009807 }
9808
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009809 /* NOTE: the following code can't call back into Python code,
9810 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009811 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009812
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009813 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009814 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009815 res = _PyUnicode_JoinArray(separator, items, seqlen);
9816 Py_DECREF(fseq);
9817 return res;
9818}
9819
9820PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009821_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009822{
9823 PyObject *res = NULL; /* the result */
9824 PyObject *sep = NULL;
9825 Py_ssize_t seplen;
9826 PyObject *item;
9827 Py_ssize_t sz, i, res_offset;
9828 Py_UCS4 maxchar;
9829 Py_UCS4 item_maxchar;
9830 int use_memcpy;
9831 unsigned char *res_data = NULL, *sep_data = NULL;
9832 PyObject *last_obj;
9833 unsigned int kind = 0;
9834
Tim Peters05eba1f2004-08-27 21:32:02 +00009835 /* If empty sequence, return u"". */
9836 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009837 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009838 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009839
Tim Peters05eba1f2004-08-27 21:32:02 +00009840 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009841 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009842 if (seqlen == 1) {
9843 if (PyUnicode_CheckExact(items[0])) {
9844 res = items[0];
9845 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009846 return res;
9847 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009848 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009849 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009850 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009851 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009852 /* Set up sep and seplen */
9853 if (separator == NULL) {
9854 /* fall back to a blank space separator */
9855 sep = PyUnicode_FromOrdinal(' ');
9856 if (!sep)
9857 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009858 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009859 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009860 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009861 else {
9862 if (!PyUnicode_Check(separator)) {
9863 PyErr_Format(PyExc_TypeError,
9864 "separator: expected str instance,"
9865 " %.80s found",
9866 Py_TYPE(separator)->tp_name);
9867 goto onError;
9868 }
9869 if (PyUnicode_READY(separator))
9870 goto onError;
9871 sep = separator;
9872 seplen = PyUnicode_GET_LENGTH(separator);
9873 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9874 /* inc refcount to keep this code path symmetric with the
9875 above case of a blank separator */
9876 Py_INCREF(sep);
9877 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009878 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009879 }
9880
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009881 /* There are at least two things to join, or else we have a subclass
9882 * of str in the sequence.
9883 * Do a pre-pass to figure out the total amount of space we'll
9884 * need (sz), and see whether all argument are strings.
9885 */
9886 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009887#ifdef Py_DEBUG
9888 use_memcpy = 0;
9889#else
9890 use_memcpy = 1;
9891#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009892 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009893 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009894 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009895 if (!PyUnicode_Check(item)) {
9896 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009897 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009898 " %.80s found",
9899 i, Py_TYPE(item)->tp_name);
9900 goto onError;
9901 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009902 if (PyUnicode_READY(item) == -1)
9903 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009904 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009906 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009907 if (i != 0) {
9908 add_sz += seplen;
9909 }
9910 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009911 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009912 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009913 goto onError;
9914 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009915 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009916 if (use_memcpy && last_obj != NULL) {
9917 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9918 use_memcpy = 0;
9919 }
9920 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009921 }
Tim Petersced69f82003-09-16 20:30:58 +00009922
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009923 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009924 if (res == NULL)
9925 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009926
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009927 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009928#ifdef Py_DEBUG
9929 use_memcpy = 0;
9930#else
9931 if (use_memcpy) {
9932 res_data = PyUnicode_1BYTE_DATA(res);
9933 kind = PyUnicode_KIND(res);
9934 if (seplen != 0)
9935 sep_data = PyUnicode_1BYTE_DATA(sep);
9936 }
9937#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009938 if (use_memcpy) {
9939 for (i = 0; i < seqlen; ++i) {
9940 Py_ssize_t itemlen;
9941 item = items[i];
9942
9943 /* Copy item, and maybe the separator. */
9944 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009945 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009946 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009947 kind * seplen);
9948 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009949 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009950
9951 itemlen = PyUnicode_GET_LENGTH(item);
9952 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009953 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009954 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009955 kind * itemlen);
9956 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009957 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009958 }
9959 assert(res_data == PyUnicode_1BYTE_DATA(res)
9960 + kind * PyUnicode_GET_LENGTH(res));
9961 }
9962 else {
9963 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9964 Py_ssize_t itemlen;
9965 item = items[i];
9966
9967 /* Copy item, and maybe the separator. */
9968 if (i && seplen != 0) {
9969 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9970 res_offset += seplen;
9971 }
9972
9973 itemlen = PyUnicode_GET_LENGTH(item);
9974 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009975 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009976 res_offset += itemlen;
9977 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009978 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009979 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009980 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009981
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009983 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009985
Benjamin Peterson29060642009-01-31 22:14:21 +00009986 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009988 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009989 return NULL;
9990}
9991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009992#define FILL(kind, data, value, start, length) \
9993 do { \
9994 Py_ssize_t i_ = 0; \
9995 assert(kind != PyUnicode_WCHAR_KIND); \
9996 switch ((kind)) { \
9997 case PyUnicode_1BYTE_KIND: { \
9998 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009999 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 break; \
10001 } \
10002 case PyUnicode_2BYTE_KIND: { \
10003 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10004 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10005 break; \
10006 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010007 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10009 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10010 break; \
10011 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010012 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 } \
10014 } while (0)
10015
Victor Stinnerd3f08822012-05-29 12:57:52 +020010016void
10017_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10018 Py_UCS4 fill_char)
10019{
10020 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10021 const void *data = PyUnicode_DATA(unicode);
10022 assert(PyUnicode_IS_READY(unicode));
10023 assert(unicode_modifiable(unicode));
10024 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10025 assert(start >= 0);
10026 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10027 FILL(kind, data, fill_char, start, length);
10028}
10029
Victor Stinner3fe55312012-01-04 00:33:50 +010010030Py_ssize_t
10031PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10032 Py_UCS4 fill_char)
10033{
10034 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010035
10036 if (!PyUnicode_Check(unicode)) {
10037 PyErr_BadInternalCall();
10038 return -1;
10039 }
10040 if (PyUnicode_READY(unicode) == -1)
10041 return -1;
10042 if (unicode_check_modifiable(unicode))
10043 return -1;
10044
Victor Stinnerd3f08822012-05-29 12:57:52 +020010045 if (start < 0) {
10046 PyErr_SetString(PyExc_IndexError, "string index out of range");
10047 return -1;
10048 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010049 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10050 PyErr_SetString(PyExc_ValueError,
10051 "fill character is bigger than "
10052 "the string maximum character");
10053 return -1;
10054 }
10055
10056 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10057 length = Py_MIN(maxlen, length);
10058 if (length <= 0)
10059 return 0;
10060
Victor Stinnerd3f08822012-05-29 12:57:52 +020010061 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010062 return length;
10063}
10064
Victor Stinner9310abb2011-10-05 00:59:23 +020010065static PyObject *
10066pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010067 Py_ssize_t left,
10068 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010070{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 PyObject *u;
10072 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010073 int kind;
10074 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010075
10076 if (left < 0)
10077 left = 0;
10078 if (right < 0)
10079 right = 0;
10080
Victor Stinnerc4b49542011-12-11 22:44:26 +010010081 if (left == 0 && right == 0)
10082 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10085 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010086 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10087 return NULL;
10088 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010090 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010092 if (!u)
10093 return NULL;
10094
10095 kind = PyUnicode_KIND(u);
10096 data = PyUnicode_DATA(u);
10097 if (left)
10098 FILL(kind, data, fill, 0, left);
10099 if (right)
10100 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010101 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010102 assert(_PyUnicode_CheckConsistency(u, 1));
10103 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010104}
10105
Alexander Belopolsky40018472011-02-26 01:02:56 +000010106PyObject *
10107PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010108{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010110
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010111 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010112 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010113
Benjamin Petersonead6b532011-12-20 17:23:42 -060010114 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010116 if (PyUnicode_IS_ASCII(string))
10117 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010118 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010119 PyUnicode_GET_LENGTH(string), keepends);
10120 else
10121 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010122 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010123 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 break;
10125 case PyUnicode_2BYTE_KIND:
10126 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010127 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 PyUnicode_GET_LENGTH(string), keepends);
10129 break;
10130 case PyUnicode_4BYTE_KIND:
10131 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010132 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 PyUnicode_GET_LENGTH(string), keepends);
10134 break;
10135 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010136 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010138 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139}
10140
Alexander Belopolsky40018472011-02-26 01:02:56 +000010141static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010142split(PyObject *self,
10143 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010144 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010145{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010146 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 void *buf1, *buf2;
10148 Py_ssize_t len1, len2;
10149 PyObject* out;
10150
Guido van Rossumd57fd912000-03-10 22:53:23 +000010151 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010152 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010153
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 if (PyUnicode_READY(self) == -1)
10155 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010158 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010160 if (PyUnicode_IS_ASCII(self))
10161 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010162 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010163 PyUnicode_GET_LENGTH(self), maxcount
10164 );
10165 else
10166 return ucs1lib_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 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 case PyUnicode_2BYTE_KIND:
10171 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010172 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 PyUnicode_GET_LENGTH(self), maxcount
10174 );
10175 case PyUnicode_4BYTE_KIND:
10176 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010177 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 PyUnicode_GET_LENGTH(self), maxcount
10179 );
10180 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010181 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 }
10183
10184 if (PyUnicode_READY(substring) == -1)
10185 return NULL;
10186
10187 kind1 = PyUnicode_KIND(self);
10188 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 len1 = PyUnicode_GET_LENGTH(self);
10190 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010191 if (kind1 < kind2 || len1 < len2) {
10192 out = PyList_New(1);
10193 if (out == NULL)
10194 return NULL;
10195 Py_INCREF(self);
10196 PyList_SET_ITEM(out, 0, self);
10197 return out;
10198 }
10199 buf1 = PyUnicode_DATA(self);
10200 buf2 = PyUnicode_DATA(substring);
10201 if (kind2 != kind1) {
10202 buf2 = _PyUnicode_AsKind(substring, kind1);
10203 if (!buf2)
10204 return NULL;
10205 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010207 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010209 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10210 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010211 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010212 else
10213 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010214 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 break;
10216 case PyUnicode_2BYTE_KIND:
10217 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010218 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 break;
10220 case PyUnicode_4BYTE_KIND:
10221 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010222 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 break;
10224 default:
10225 out = NULL;
10226 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010227 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 PyMem_Free(buf2);
10229 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010230}
10231
Alexander Belopolsky40018472011-02-26 01:02:56 +000010232static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010233rsplit(PyObject *self,
10234 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010235 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010236{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010237 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 void *buf1, *buf2;
10239 Py_ssize_t len1, len2;
10240 PyObject* out;
10241
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010242 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010243 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010244
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 if (PyUnicode_READY(self) == -1)
10246 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010247
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010249 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010251 if (PyUnicode_IS_ASCII(self))
10252 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010253 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010254 PyUnicode_GET_LENGTH(self), maxcount
10255 );
10256 else
10257 return ucs1lib_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 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 case PyUnicode_2BYTE_KIND:
10262 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010263 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 PyUnicode_GET_LENGTH(self), maxcount
10265 );
10266 case PyUnicode_4BYTE_KIND:
10267 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010268 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 PyUnicode_GET_LENGTH(self), maxcount
10270 );
10271 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010272 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 }
10274
10275 if (PyUnicode_READY(substring) == -1)
10276 return NULL;
10277
10278 kind1 = PyUnicode_KIND(self);
10279 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 len1 = PyUnicode_GET_LENGTH(self);
10281 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010282 if (kind1 < kind2 || len1 < len2) {
10283 out = PyList_New(1);
10284 if (out == NULL)
10285 return NULL;
10286 Py_INCREF(self);
10287 PyList_SET_ITEM(out, 0, self);
10288 return out;
10289 }
10290 buf1 = PyUnicode_DATA(self);
10291 buf2 = PyUnicode_DATA(substring);
10292 if (kind2 != kind1) {
10293 buf2 = _PyUnicode_AsKind(substring, kind1);
10294 if (!buf2)
10295 return NULL;
10296 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010298 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010300 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10301 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010302 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010303 else
10304 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010305 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306 break;
10307 case PyUnicode_2BYTE_KIND:
10308 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010309 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 break;
10311 case PyUnicode_4BYTE_KIND:
10312 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010313 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 break;
10315 default:
10316 out = NULL;
10317 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010318 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 PyMem_Free(buf2);
10320 return out;
10321}
10322
10323static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010324anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10325 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010327 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010329 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10330 return asciilib_find(buf1, len1, buf2, len2, offset);
10331 else
10332 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 case PyUnicode_2BYTE_KIND:
10334 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10335 case PyUnicode_4BYTE_KIND:
10336 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10337 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010338 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339}
10340
10341static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010342anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10343 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010345 switch (kind) {
10346 case PyUnicode_1BYTE_KIND:
10347 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10348 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10349 else
10350 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10351 case PyUnicode_2BYTE_KIND:
10352 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10353 case PyUnicode_4BYTE_KIND:
10354 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10355 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010356 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010357}
10358
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010359static void
10360replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10361 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10362{
10363 int kind = PyUnicode_KIND(u);
10364 void *data = PyUnicode_DATA(u);
10365 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10366 if (kind == PyUnicode_1BYTE_KIND) {
10367 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10368 (Py_UCS1 *)data + len,
10369 u1, u2, maxcount);
10370 }
10371 else if (kind == PyUnicode_2BYTE_KIND) {
10372 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10373 (Py_UCS2 *)data + len,
10374 u1, u2, maxcount);
10375 }
10376 else {
10377 assert(kind == PyUnicode_4BYTE_KIND);
10378 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10379 (Py_UCS4 *)data + len,
10380 u1, u2, maxcount);
10381 }
10382}
10383
Alexander Belopolsky40018472011-02-26 01:02:56 +000010384static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385replace(PyObject *self, PyObject *str1,
10386 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 PyObject *u;
10389 char *sbuf = PyUnicode_DATA(self);
10390 char *buf1 = PyUnicode_DATA(str1);
10391 char *buf2 = PyUnicode_DATA(str2);
10392 int srelease = 0, release1 = 0, release2 = 0;
10393 int skind = PyUnicode_KIND(self);
10394 int kind1 = PyUnicode_KIND(str1);
10395 int kind2 = PyUnicode_KIND(str2);
10396 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10397 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10398 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010399 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010400 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401
10402 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010403 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010405 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010406
Victor Stinner59de0ee2011-10-07 10:01:28 +020010407 if (str1 == str2)
10408 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409
Victor Stinner49a0a212011-10-12 23:46:10 +020010410 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010411 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10412 if (maxchar < maxchar_str1)
10413 /* substring too wide to be present */
10414 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010415 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10416 /* Replacing str1 with str2 may cause a maxchar reduction in the
10417 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010418 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010419 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010422 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010424 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010426 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010427 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010428 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010429
Victor Stinner69ed0f42013-04-09 21:48:24 +020010430 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010431 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010432 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010433 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010434 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010436 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010438
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010439 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10440 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010441 }
10442 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 int rkind = skind;
10444 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010445 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 if (kind1 < rkind) {
10448 /* widen substring */
10449 buf1 = _PyUnicode_AsKind(str1, rkind);
10450 if (!buf1) goto error;
10451 release1 = 1;
10452 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010453 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010454 if (i < 0)
10455 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 if (rkind > kind2) {
10457 /* widen replacement */
10458 buf2 = _PyUnicode_AsKind(str2, rkind);
10459 if (!buf2) goto error;
10460 release2 = 1;
10461 }
10462 else if (rkind < kind2) {
10463 /* widen self and buf1 */
10464 rkind = kind2;
10465 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010466 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 sbuf = _PyUnicode_AsKind(self, rkind);
10468 if (!sbuf) goto error;
10469 srelease = 1;
10470 buf1 = _PyUnicode_AsKind(str1, rkind);
10471 if (!buf1) goto error;
10472 release1 = 1;
10473 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010474 u = PyUnicode_New(slen, maxchar);
10475 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010477 assert(PyUnicode_KIND(u) == rkind);
10478 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010479
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010480 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010481 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010482 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010484 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010486
10487 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010488 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010489 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010490 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010491 if (i == -1)
10492 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010493 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010494 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010495 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010497 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010498 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010499 }
10500 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010502 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 int rkind = skind;
10504 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010505
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010507 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508 buf1 = _PyUnicode_AsKind(str1, rkind);
10509 if (!buf1) goto error;
10510 release1 = 1;
10511 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010512 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010513 if (n == 0)
10514 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010516 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 buf2 = _PyUnicode_AsKind(str2, rkind);
10518 if (!buf2) goto error;
10519 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010522 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 rkind = kind2;
10524 sbuf = _PyUnicode_AsKind(self, rkind);
10525 if (!sbuf) goto error;
10526 srelease = 1;
10527 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010528 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 buf1 = _PyUnicode_AsKind(str1, rkind);
10530 if (!buf1) goto error;
10531 release1 = 1;
10532 }
10533 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10534 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010535 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 PyErr_SetString(PyExc_OverflowError,
10537 "replace string is too long");
10538 goto error;
10539 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010540 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010541 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010542 _Py_INCREF_UNICODE_EMPTY();
10543 if (!unicode_empty)
10544 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010545 u = unicode_empty;
10546 goto done;
10547 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010548 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 PyErr_SetString(PyExc_OverflowError,
10550 "replace string is too long");
10551 goto error;
10552 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010553 u = PyUnicode_New(new_size, maxchar);
10554 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010556 assert(PyUnicode_KIND(u) == rkind);
10557 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 ires = i = 0;
10559 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010560 while (n-- > 0) {
10561 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010562 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010563 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010564 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010565 if (j == -1)
10566 break;
10567 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010568 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010569 memcpy(res + rkind * ires,
10570 sbuf + rkind * i,
10571 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010573 }
10574 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010576 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010578 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010580 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010584 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010585 memcpy(res + rkind * ires,
10586 sbuf + rkind * i,
10587 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010588 }
10589 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010590 /* interleave */
10591 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010592 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010594 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010596 if (--n <= 0)
10597 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010598 memcpy(res + rkind * ires,
10599 sbuf + rkind * i,
10600 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 ires++;
10602 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010603 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010604 memcpy(res + rkind * ires,
10605 sbuf + rkind * i,
10606 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010607 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010608 }
10609
10610 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010611 unicode_adjust_maxchar(&u);
10612 if (u == NULL)
10613 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010614 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010615
10616 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 if (srelease)
10618 PyMem_FREE(sbuf);
10619 if (release1)
10620 PyMem_FREE(buf1);
10621 if (release2)
10622 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010623 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010625
Benjamin Peterson29060642009-01-31 22:14:21 +000010626 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010627 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 if (srelease)
10629 PyMem_FREE(sbuf);
10630 if (release1)
10631 PyMem_FREE(buf1);
10632 if (release2)
10633 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010634 return unicode_result_unchanged(self);
10635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 error:
10637 if (srelease && sbuf)
10638 PyMem_FREE(sbuf);
10639 if (release1 && buf1)
10640 PyMem_FREE(buf1);
10641 if (release2 && buf2)
10642 PyMem_FREE(buf2);
10643 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644}
10645
10646/* --- Unicode Object Methods --------------------------------------------- */
10647
INADA Naoki3ae20562017-01-16 20:41:20 +090010648/*[clinic input]
10649str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010650
INADA Naoki3ae20562017-01-16 20:41:20 +090010651Return a version of the string where each word is titlecased.
10652
10653More specifically, words start with uppercased characters and all remaining
10654cased characters have lower case.
10655[clinic start generated code]*/
10656
10657static PyObject *
10658unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010659/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010660{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010661 if (PyUnicode_READY(self) == -1)
10662 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010663 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664}
10665
INADA Naoki3ae20562017-01-16 20:41:20 +090010666/*[clinic input]
10667str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010668
INADA Naoki3ae20562017-01-16 20:41:20 +090010669Return a capitalized version of the string.
10670
10671More specifically, make the first character have upper case and the rest lower
10672case.
10673[clinic start generated code]*/
10674
10675static PyObject *
10676unicode_capitalize_impl(PyObject *self)
10677/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010678{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010679 if (PyUnicode_READY(self) == -1)
10680 return NULL;
10681 if (PyUnicode_GET_LENGTH(self) == 0)
10682 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010683 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010684}
10685
INADA Naoki3ae20562017-01-16 20:41:20 +090010686/*[clinic input]
10687str.casefold as unicode_casefold
10688
10689Return a version of the string suitable for caseless comparisons.
10690[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010691
10692static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010693unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010694/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010695{
10696 if (PyUnicode_READY(self) == -1)
10697 return NULL;
10698 if (PyUnicode_IS_ASCII(self))
10699 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010700 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010701}
10702
10703
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010704/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010705
10706static int
10707convert_uc(PyObject *obj, void *addr)
10708{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010710
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010711 if (!PyUnicode_Check(obj)) {
10712 PyErr_Format(PyExc_TypeError,
10713 "The fill character must be a unicode character, "
10714 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010715 return 0;
10716 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010717 if (PyUnicode_READY(obj) < 0)
10718 return 0;
10719 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010720 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010721 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010722 return 0;
10723 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010724 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010725 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010726}
10727
INADA Naoki3ae20562017-01-16 20:41:20 +090010728/*[clinic input]
10729str.center as unicode_center
10730
10731 width: Py_ssize_t
10732 fillchar: Py_UCS4 = ' '
10733 /
10734
10735Return a centered string of length width.
10736
10737Padding is done using the specified fill character (default is a space).
10738[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010739
10740static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010741unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10742/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010743{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010744 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010745
Benjamin Petersonbac79492012-01-14 13:34:47 -050010746 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010747 return NULL;
10748
Victor Stinnerc4b49542011-12-11 22:44:26 +010010749 if (PyUnicode_GET_LENGTH(self) >= width)
10750 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751
Victor Stinnerc4b49542011-12-11 22:44:26 +010010752 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010753 left = marg / 2 + (marg & width & 1);
10754
Victor Stinner9310abb2011-10-05 00:59:23 +020010755 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756}
10757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758/* This function assumes that str1 and str2 are readied by the caller. */
10759
Marc-André Lemburge5034372000-08-08 08:04:29 +000010760static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010761unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010762{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010763#define COMPARE(TYPE1, TYPE2) \
10764 do { \
10765 TYPE1* p1 = (TYPE1 *)data1; \
10766 TYPE2* p2 = (TYPE2 *)data2; \
10767 TYPE1* end = p1 + len; \
10768 Py_UCS4 c1, c2; \
10769 for (; p1 != end; p1++, p2++) { \
10770 c1 = *p1; \
10771 c2 = *p2; \
10772 if (c1 != c2) \
10773 return (c1 < c2) ? -1 : 1; \
10774 } \
10775 } \
10776 while (0)
10777
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010778 int kind1, kind2;
10779 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010780 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 kind1 = PyUnicode_KIND(str1);
10783 kind2 = PyUnicode_KIND(str2);
10784 data1 = PyUnicode_DATA(str1);
10785 data2 = PyUnicode_DATA(str2);
10786 len1 = PyUnicode_GET_LENGTH(str1);
10787 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010788 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010789
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010790 switch(kind1) {
10791 case PyUnicode_1BYTE_KIND:
10792 {
10793 switch(kind2) {
10794 case PyUnicode_1BYTE_KIND:
10795 {
10796 int cmp = memcmp(data1, data2, len);
10797 /* normalize result of memcmp() into the range [-1; 1] */
10798 if (cmp < 0)
10799 return -1;
10800 if (cmp > 0)
10801 return 1;
10802 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010803 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010804 case PyUnicode_2BYTE_KIND:
10805 COMPARE(Py_UCS1, Py_UCS2);
10806 break;
10807 case PyUnicode_4BYTE_KIND:
10808 COMPARE(Py_UCS1, Py_UCS4);
10809 break;
10810 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010811 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010812 }
10813 break;
10814 }
10815 case PyUnicode_2BYTE_KIND:
10816 {
10817 switch(kind2) {
10818 case PyUnicode_1BYTE_KIND:
10819 COMPARE(Py_UCS2, Py_UCS1);
10820 break;
10821 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010822 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010823 COMPARE(Py_UCS2, Py_UCS2);
10824 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010825 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010826 case PyUnicode_4BYTE_KIND:
10827 COMPARE(Py_UCS2, Py_UCS4);
10828 break;
10829 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010830 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010831 }
10832 break;
10833 }
10834 case PyUnicode_4BYTE_KIND:
10835 {
10836 switch(kind2) {
10837 case PyUnicode_1BYTE_KIND:
10838 COMPARE(Py_UCS4, Py_UCS1);
10839 break;
10840 case PyUnicode_2BYTE_KIND:
10841 COMPARE(Py_UCS4, Py_UCS2);
10842 break;
10843 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010844 {
10845#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10846 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10847 /* normalize result of wmemcmp() into the range [-1; 1] */
10848 if (cmp < 0)
10849 return -1;
10850 if (cmp > 0)
10851 return 1;
10852#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010853 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010854#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010855 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010856 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010857 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010858 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010859 }
10860 break;
10861 }
10862 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010863 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010864 }
10865
Victor Stinner770e19e2012-10-04 22:59:45 +020010866 if (len1 == len2)
10867 return 0;
10868 if (len1 < len2)
10869 return -1;
10870 else
10871 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010872
10873#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010874}
10875
Benjamin Peterson621b4302016-09-09 13:54:34 -070010876static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010877unicode_compare_eq(PyObject *str1, PyObject *str2)
10878{
10879 int kind;
10880 void *data1, *data2;
10881 Py_ssize_t len;
10882 int cmp;
10883
Victor Stinnere5567ad2012-10-23 02:48:49 +020010884 len = PyUnicode_GET_LENGTH(str1);
10885 if (PyUnicode_GET_LENGTH(str2) != len)
10886 return 0;
10887 kind = PyUnicode_KIND(str1);
10888 if (PyUnicode_KIND(str2) != kind)
10889 return 0;
10890 data1 = PyUnicode_DATA(str1);
10891 data2 = PyUnicode_DATA(str2);
10892
10893 cmp = memcmp(data1, data2, len * kind);
10894 return (cmp == 0);
10895}
10896
10897
Alexander Belopolsky40018472011-02-26 01:02:56 +000010898int
10899PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010900{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010901 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10902 if (PyUnicode_READY(left) == -1 ||
10903 PyUnicode_READY(right) == -1)
10904 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010905
10906 /* a string is equal to itself */
10907 if (left == right)
10908 return 0;
10909
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010910 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010911 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010912 PyErr_Format(PyExc_TypeError,
10913 "Can't compare %.100s and %.100s",
10914 left->ob_type->tp_name,
10915 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916 return -1;
10917}
10918
Martin v. Löwis5b222132007-06-10 09:51:05 +000010919int
10920PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10921{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010922 Py_ssize_t i;
10923 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010925 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010926
Victor Stinner910337b2011-10-03 03:20:16 +020010927 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010928 if (!PyUnicode_IS_READY(uni)) {
10929 const wchar_t *ws = _PyUnicode_WSTR(uni);
10930 /* Compare Unicode string and source character set string */
10931 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10932 if (chr != ustr[i])
10933 return (chr < ustr[i]) ? -1 : 1;
10934 }
10935 /* This check keeps Python strings that end in '\0' from comparing equal
10936 to C strings identical up to that point. */
10937 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10938 return 1; /* uni is longer */
10939 if (ustr[i])
10940 return -1; /* str is longer */
10941 return 0;
10942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010943 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010944 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010945 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010946 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010947 size_t len, len2 = strlen(str);
10948 int cmp;
10949
10950 len = Py_MIN(len1, len2);
10951 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010952 if (cmp != 0) {
10953 if (cmp < 0)
10954 return -1;
10955 else
10956 return 1;
10957 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010958 if (len1 > len2)
10959 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010960 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010961 return -1; /* str is longer */
10962 return 0;
10963 }
10964 else {
10965 void *data = PyUnicode_DATA(uni);
10966 /* Compare Unicode string and source character set string */
10967 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010968 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010969 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10970 /* This check keeps Python strings that end in '\0' from comparing equal
10971 to C strings identical up to that point. */
10972 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10973 return 1; /* uni is longer */
10974 if (str[i])
10975 return -1; /* str is longer */
10976 return 0;
10977 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010978}
10979
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010980static int
10981non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
10982{
10983 size_t i, len;
10984 const wchar_t *p;
10985 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
10986 if (strlen(str) != len)
10987 return 0;
10988 p = _PyUnicode_WSTR(unicode);
10989 assert(p);
10990 for (i = 0; i < len; i++) {
10991 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020010992 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010993 return 0;
10994 }
10995 return 1;
10996}
10997
10998int
10999_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11000{
11001 size_t len;
11002 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011003 assert(str);
11004#ifndef NDEBUG
11005 for (const char *p = str; *p; p++) {
11006 assert((unsigned char)*p < 128);
11007 }
11008#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011009 if (PyUnicode_READY(unicode) == -1) {
11010 /* Memory error or bad data */
11011 PyErr_Clear();
11012 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11013 }
11014 if (!PyUnicode_IS_ASCII(unicode))
11015 return 0;
11016 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11017 return strlen(str) == len &&
11018 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11019}
11020
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011021int
11022_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11023{
11024 PyObject *right_uni;
11025 Py_hash_t hash;
11026
11027 assert(_PyUnicode_CHECK(left));
11028 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011029#ifndef NDEBUG
11030 for (const char *p = right->string; *p; p++) {
11031 assert((unsigned char)*p < 128);
11032 }
11033#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011034
11035 if (PyUnicode_READY(left) == -1) {
11036 /* memory error or bad data */
11037 PyErr_Clear();
11038 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11039 }
11040
11041 if (!PyUnicode_IS_ASCII(left))
11042 return 0;
11043
11044 right_uni = _PyUnicode_FromId(right); /* borrowed */
11045 if (right_uni == NULL) {
11046 /* memory error or bad data */
11047 PyErr_Clear();
11048 return _PyUnicode_EqualToASCIIString(left, right->string);
11049 }
11050
11051 if (left == right_uni)
11052 return 1;
11053
11054 if (PyUnicode_CHECK_INTERNED(left))
11055 return 0;
11056
INADA Naoki7cc95f52018-01-28 02:07:09 +090011057 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011058 hash = _PyUnicode_HASH(left);
11059 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11060 return 0;
11061
11062 return unicode_compare_eq(left, right_uni);
11063}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011064
Alexander Belopolsky40018472011-02-26 01:02:56 +000011065PyObject *
11066PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011067{
11068 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011069
Victor Stinnere5567ad2012-10-23 02:48:49 +020011070 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11071 Py_RETURN_NOTIMPLEMENTED;
11072
11073 if (PyUnicode_READY(left) == -1 ||
11074 PyUnicode_READY(right) == -1)
11075 return NULL;
11076
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011077 if (left == right) {
11078 switch (op) {
11079 case Py_EQ:
11080 case Py_LE:
11081 case Py_GE:
11082 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011083 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011084 case Py_NE:
11085 case Py_LT:
11086 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011087 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011088 default:
11089 PyErr_BadArgument();
11090 return NULL;
11091 }
11092 }
11093 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011094 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011095 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011096 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011097 }
11098 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011099 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011100 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011101 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011102}
11103
Alexander Belopolsky40018472011-02-26 01:02:56 +000011104int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011105_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11106{
11107 return unicode_eq(aa, bb);
11108}
11109
11110int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011111PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011112{
Victor Stinner77282cb2013-04-14 19:22:47 +020011113 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 void *buf1, *buf2;
11115 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011116 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011117
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011118 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011119 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011120 "'in <string>' requires string as left operand, not %.100s",
11121 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011122 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011123 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011124 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011125 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011126 if (ensure_unicode(str) < 0)
11127 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011130 kind2 = PyUnicode_KIND(substr);
11131 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011132 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011133 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011134 len2 = PyUnicode_GET_LENGTH(substr);
11135 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011136 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011137 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011138 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011139 if (len2 == 1) {
11140 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11141 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011142 return result;
11143 }
11144 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011145 buf2 = _PyUnicode_AsKind(substr, kind1);
11146 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011147 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149
Victor Stinner77282cb2013-04-14 19:22:47 +020011150 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 case PyUnicode_1BYTE_KIND:
11152 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11153 break;
11154 case PyUnicode_2BYTE_KIND:
11155 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11156 break;
11157 case PyUnicode_4BYTE_KIND:
11158 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11159 break;
11160 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011161 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011162 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011163
Victor Stinner77282cb2013-04-14 19:22:47 +020011164 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 PyMem_Free(buf2);
11166
Guido van Rossum403d68b2000-03-13 15:55:09 +000011167 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011168}
11169
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170/* Concat to string or Unicode object giving a new Unicode object. */
11171
Alexander Belopolsky40018472011-02-26 01:02:56 +000011172PyObject *
11173PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011175 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011176 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011177 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011179 if (ensure_unicode(left) < 0)
11180 return NULL;
11181
11182 if (!PyUnicode_Check(right)) {
11183 PyErr_Format(PyExc_TypeError,
11184 "can only concatenate str (not \"%.200s\") to str",
11185 right->ob_type->tp_name);
11186 return NULL;
11187 }
11188 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011189 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190
11191 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011192 if (left == unicode_empty)
11193 return PyUnicode_FromObject(right);
11194 if (right == unicode_empty)
11195 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011197 left_len = PyUnicode_GET_LENGTH(left);
11198 right_len = PyUnicode_GET_LENGTH(right);
11199 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011200 PyErr_SetString(PyExc_OverflowError,
11201 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011202 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011203 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011204 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011205
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011206 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11207 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011208 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011211 result = PyUnicode_New(new_len, maxchar);
11212 if (result == NULL)
11213 return NULL;
11214 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11215 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11216 assert(_PyUnicode_CheckConsistency(result, 1));
11217 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218}
11219
Walter Dörwald1ab83302007-05-18 17:15:44 +000011220void
Victor Stinner23e56682011-10-03 03:54:37 +020011221PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011222{
Victor Stinner23e56682011-10-03 03:54:37 +020011223 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011224 Py_UCS4 maxchar, maxchar2;
11225 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011226
11227 if (p_left == NULL) {
11228 if (!PyErr_Occurred())
11229 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011230 return;
11231 }
Victor Stinner23e56682011-10-03 03:54:37 +020011232 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011233 if (right == NULL || left == NULL
11234 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011235 if (!PyErr_Occurred())
11236 PyErr_BadInternalCall();
11237 goto error;
11238 }
11239
Benjamin Petersonbac79492012-01-14 13:34:47 -050011240 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011241 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011242 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011243 goto error;
11244
Victor Stinner488fa492011-12-12 00:01:39 +010011245 /* Shortcuts */
11246 if (left == unicode_empty) {
11247 Py_DECREF(left);
11248 Py_INCREF(right);
11249 *p_left = right;
11250 return;
11251 }
11252 if (right == unicode_empty)
11253 return;
11254
11255 left_len = PyUnicode_GET_LENGTH(left);
11256 right_len = PyUnicode_GET_LENGTH(right);
11257 if (left_len > PY_SSIZE_T_MAX - right_len) {
11258 PyErr_SetString(PyExc_OverflowError,
11259 "strings are too large to concat");
11260 goto error;
11261 }
11262 new_len = left_len + right_len;
11263
11264 if (unicode_modifiable(left)
11265 && PyUnicode_CheckExact(right)
11266 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011267 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11268 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011269 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011270 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011271 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11272 {
11273 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011274 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011275 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011276
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011277 /* copy 'right' into the newly allocated area of 'left' */
11278 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011279 }
Victor Stinner488fa492011-12-12 00:01:39 +010011280 else {
11281 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11282 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011283 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011284
Victor Stinner488fa492011-12-12 00:01:39 +010011285 /* Concat the two Unicode strings */
11286 res = PyUnicode_New(new_len, maxchar);
11287 if (res == NULL)
11288 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011289 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11290 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011291 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011292 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011293 }
11294 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011295 return;
11296
11297error:
Victor Stinner488fa492011-12-12 00:01:39 +010011298 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011299}
11300
11301void
11302PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11303{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011304 PyUnicode_Append(pleft, right);
11305 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011306}
11307
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011308/*
11309Wraps stringlib_parse_args_finds() and additionally ensures that the
11310first argument is a unicode object.
11311*/
11312
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011313static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011314parse_args_finds_unicode(const char * function_name, PyObject *args,
11315 PyObject **substring,
11316 Py_ssize_t *start, Py_ssize_t *end)
11317{
11318 if(stringlib_parse_args_finds(function_name, args, substring,
11319 start, end)) {
11320 if (ensure_unicode(*substring) < 0)
11321 return 0;
11322 return 1;
11323 }
11324 return 0;
11325}
11326
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011327PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011328 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011330Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011331string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011332interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333
11334static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011335unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011337 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011338 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011339 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011341 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011342 void *buf1, *buf2;
11343 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011345 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011346 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011348 kind1 = PyUnicode_KIND(self);
11349 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011350 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011351 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 len1 = PyUnicode_GET_LENGTH(self);
11354 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011355 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011356 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011357 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011358
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011359 buf1 = PyUnicode_DATA(self);
11360 buf2 = PyUnicode_DATA(substring);
11361 if (kind2 != kind1) {
11362 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011363 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011364 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011365 }
11366 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 case PyUnicode_1BYTE_KIND:
11368 iresult = ucs1lib_count(
11369 ((Py_UCS1*)buf1) + start, end - start,
11370 buf2, len2, PY_SSIZE_T_MAX
11371 );
11372 break;
11373 case PyUnicode_2BYTE_KIND:
11374 iresult = ucs2lib_count(
11375 ((Py_UCS2*)buf1) + start, end - start,
11376 buf2, len2, PY_SSIZE_T_MAX
11377 );
11378 break;
11379 case PyUnicode_4BYTE_KIND:
11380 iresult = ucs4lib_count(
11381 ((Py_UCS4*)buf1) + start, end - start,
11382 buf2, len2, PY_SSIZE_T_MAX
11383 );
11384 break;
11385 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011386 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 }
11388
11389 result = PyLong_FromSsize_t(iresult);
11390
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011391 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394 return result;
11395}
11396
INADA Naoki3ae20562017-01-16 20:41:20 +090011397/*[clinic input]
11398str.encode as unicode_encode
11399
11400 encoding: str(c_default="NULL") = 'utf-8'
11401 The encoding in which to encode the string.
11402 errors: str(c_default="NULL") = 'strict'
11403 The error handling scheme to use for encoding errors.
11404 The default is 'strict' meaning that encoding errors raise a
11405 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11406 'xmlcharrefreplace' as well as any other name registered with
11407 codecs.register_error that can handle UnicodeEncodeErrors.
11408
11409Encode the string using the codec registered for encoding.
11410[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411
11412static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011413unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011414/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011416 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011417}
11418
INADA Naoki3ae20562017-01-16 20:41:20 +090011419/*[clinic input]
11420str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
INADA Naoki3ae20562017-01-16 20:41:20 +090011422 tabsize: int = 8
11423
11424Return a copy where all tab characters are expanded using spaces.
11425
11426If tabsize is not given, a tab size of 8 characters is assumed.
11427[clinic start generated code]*/
11428
11429static PyObject *
11430unicode_expandtabs_impl(PyObject *self, int tabsize)
11431/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011433 Py_ssize_t i, j, line_pos, src_len, incr;
11434 Py_UCS4 ch;
11435 PyObject *u;
11436 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011437 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011438 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439
Antoine Pitrou22425222011-10-04 19:10:51 +020011440 if (PyUnicode_READY(self) == -1)
11441 return NULL;
11442
Thomas Wouters7e474022000-07-16 12:04:32 +000011443 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011444 src_len = PyUnicode_GET_LENGTH(self);
11445 i = j = line_pos = 0;
11446 kind = PyUnicode_KIND(self);
11447 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011448 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011449 for (; i < src_len; i++) {
11450 ch = PyUnicode_READ(kind, src_data, i);
11451 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011452 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011453 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011454 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011456 goto overflow;
11457 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011458 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011459 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011460 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011463 goto overflow;
11464 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011466 if (ch == '\n' || ch == '\r')
11467 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011469 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011470 if (!found)
11471 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011472
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011474 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475 if (!u)
11476 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011477 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480
Antoine Pitroue71d5742011-10-04 15:55:09 +020011481 for (; i < src_len; i++) {
11482 ch = PyUnicode_READ(kind, src_data, i);
11483 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011485 incr = tabsize - (line_pos % tabsize);
11486 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011487 FILL(kind, dest_data, ' ', j, incr);
11488 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011490 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011491 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011492 line_pos++;
11493 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011494 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011495 if (ch == '\n' || ch == '\r')
11496 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011498 }
11499 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011500 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011501
Antoine Pitroue71d5742011-10-04 15:55:09 +020011502 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011503 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11504 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505}
11506
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011507PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011508 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509\n\
11510Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011511such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512arguments start and end are interpreted as in slice notation.\n\
11513\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011514Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515
11516static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011519 /* initialize variables to prevent gcc warning */
11520 PyObject *substring = NULL;
11521 Py_ssize_t start = 0;
11522 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011523 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011525 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011528 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011529 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011531 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 if (result == -2)
11534 return NULL;
11535
Christian Heimes217cfd12007-12-02 14:31:20 +000011536 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537}
11538
11539static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011540unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011542 void *data;
11543 enum PyUnicode_Kind kind;
11544 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011545
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011546 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011547 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011549 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011550 if (PyUnicode_READY(self) == -1) {
11551 return NULL;
11552 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011553 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11554 PyErr_SetString(PyExc_IndexError, "string index out of range");
11555 return NULL;
11556 }
11557 kind = PyUnicode_KIND(self);
11558 data = PyUnicode_DATA(self);
11559 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011560 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561}
11562
Guido van Rossumc2504932007-09-18 19:42:40 +000011563/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011564 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011565static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011566unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567{
Guido van Rossumc2504932007-09-18 19:42:40 +000011568 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011569 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011570
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011571#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011572 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011573#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574 if (_PyUnicode_HASH(self) != -1)
11575 return _PyUnicode_HASH(self);
11576 if (PyUnicode_READY(self) == -1)
11577 return -1;
11578 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011579 /*
11580 We make the hash of the empty string be 0, rather than using
11581 (prefix ^ suffix), since this slightly obfuscates the hash secret
11582 */
11583 if (len == 0) {
11584 _PyUnicode_HASH(self) = 0;
11585 return 0;
11586 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011587 x = _Py_HashBytes(PyUnicode_DATA(self),
11588 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011590 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591}
11592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011593PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011594 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011596Return the lowest index in S where substring sub is found, \n\
11597such that sub is contained within S[start:end]. Optional\n\
11598arguments start and end are interpreted as in slice notation.\n\
11599\n\
11600Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601
11602static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011605 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011606 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011607 PyObject *substring = NULL;
11608 Py_ssize_t start = 0;
11609 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011611 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011614 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011617 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011618
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 if (result == -2)
11620 return NULL;
11621
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622 if (result < 0) {
11623 PyErr_SetString(PyExc_ValueError, "substring not found");
11624 return NULL;
11625 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011626
Christian Heimes217cfd12007-12-02 14:31:20 +000011627 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628}
11629
INADA Naoki3ae20562017-01-16 20:41:20 +090011630/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011631str.isascii as unicode_isascii
11632
11633Return True if all characters in the string are ASCII, False otherwise.
11634
11635ASCII characters have code points in the range U+0000-U+007F.
11636Empty string is ASCII too.
11637[clinic start generated code]*/
11638
11639static PyObject *
11640unicode_isascii_impl(PyObject *self)
11641/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11642{
11643 if (PyUnicode_READY(self) == -1) {
11644 return NULL;
11645 }
11646 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11647}
11648
11649/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011650str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651
INADA Naoki3ae20562017-01-16 20:41:20 +090011652Return True if the string is a lowercase string, False otherwise.
11653
11654A string is lowercase if all cased characters in the string are lowercase and
11655there is at least one cased character in the string.
11656[clinic start generated code]*/
11657
11658static PyObject *
11659unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011660/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 Py_ssize_t i, length;
11663 int kind;
11664 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665 int cased;
11666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 if (PyUnicode_READY(self) == -1)
11668 return NULL;
11669 length = PyUnicode_GET_LENGTH(self);
11670 kind = PyUnicode_KIND(self);
11671 data = PyUnicode_DATA(self);
11672
Guido van Rossumd57fd912000-03-10 22:53:23 +000011673 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (length == 1)
11675 return PyBool_FromLong(
11676 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011678 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011679 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011680 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011681
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 for (i = 0; i < length; i++) {
11684 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011685
Benjamin Peterson29060642009-01-31 22:14:21 +000011686 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011687 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011688 else if (!cased && Py_UNICODE_ISLOWER(ch))
11689 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011691 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692}
11693
INADA Naoki3ae20562017-01-16 20:41:20 +090011694/*[clinic input]
11695str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696
INADA Naoki3ae20562017-01-16 20:41:20 +090011697Return True if the string is an uppercase string, False otherwise.
11698
11699A string is uppercase if all cased characters in the string are uppercase and
11700there is at least one cased character in the string.
11701[clinic start generated code]*/
11702
11703static PyObject *
11704unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011705/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707 Py_ssize_t i, length;
11708 int kind;
11709 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710 int cased;
11711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 if (PyUnicode_READY(self) == -1)
11713 return NULL;
11714 length = PyUnicode_GET_LENGTH(self);
11715 kind = PyUnicode_KIND(self);
11716 data = PyUnicode_DATA(self);
11717
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 if (length == 1)
11720 return PyBool_FromLong(
11721 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011723 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011725 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011726
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 for (i = 0; i < length; i++) {
11729 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011730
Benjamin Peterson29060642009-01-31 22:14:21 +000011731 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011732 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011733 else if (!cased && Py_UNICODE_ISUPPER(ch))
11734 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011736 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737}
11738
INADA Naoki3ae20562017-01-16 20:41:20 +090011739/*[clinic input]
11740str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741
INADA Naoki3ae20562017-01-16 20:41:20 +090011742Return True if the string is a title-cased string, False otherwise.
11743
11744In a title-cased string, upper- and title-case characters may only
11745follow uncased characters and lowercase characters only cased ones.
11746[clinic start generated code]*/
11747
11748static PyObject *
11749unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011750/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011752 Py_ssize_t i, length;
11753 int kind;
11754 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755 int cased, previous_is_cased;
11756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757 if (PyUnicode_READY(self) == -1)
11758 return NULL;
11759 length = PyUnicode_GET_LENGTH(self);
11760 kind = PyUnicode_KIND(self);
11761 data = PyUnicode_DATA(self);
11762
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011764 if (length == 1) {
11765 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11766 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11767 (Py_UNICODE_ISUPPER(ch) != 0));
11768 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011770 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011772 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011773
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774 cased = 0;
11775 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 for (i = 0; i < length; i++) {
11777 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011778
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11780 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011781 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011782 previous_is_cased = 1;
11783 cased = 1;
11784 }
11785 else if (Py_UNICODE_ISLOWER(ch)) {
11786 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011787 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011788 previous_is_cased = 1;
11789 cased = 1;
11790 }
11791 else
11792 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011794 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795}
11796
INADA Naoki3ae20562017-01-16 20:41:20 +090011797/*[clinic input]
11798str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011799
INADA Naoki3ae20562017-01-16 20:41:20 +090011800Return True if the string is a whitespace string, False otherwise.
11801
11802A string is whitespace if all characters in the string are whitespace and there
11803is at least one character in the string.
11804[clinic start generated code]*/
11805
11806static PyObject *
11807unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011808/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 Py_ssize_t i, length;
11811 int kind;
11812 void *data;
11813
11814 if (PyUnicode_READY(self) == -1)
11815 return NULL;
11816 length = PyUnicode_GET_LENGTH(self);
11817 kind = PyUnicode_KIND(self);
11818 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 if (length == 1)
11822 return PyBool_FromLong(
11823 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011825 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011827 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011829 for (i = 0; i < length; i++) {
11830 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011831 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011832 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011834 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011835}
11836
INADA Naoki3ae20562017-01-16 20:41:20 +090011837/*[clinic input]
11838str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011839
INADA Naoki3ae20562017-01-16 20:41:20 +090011840Return True if the string is an alphabetic string, False otherwise.
11841
11842A string is alphabetic if all characters in the string are alphabetic and there
11843is at least one character in the string.
11844[clinic start generated code]*/
11845
11846static PyObject *
11847unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011848/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011849{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011850 Py_ssize_t i, length;
11851 int kind;
11852 void *data;
11853
11854 if (PyUnicode_READY(self) == -1)
11855 return NULL;
11856 length = PyUnicode_GET_LENGTH(self);
11857 kind = PyUnicode_KIND(self);
11858 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011859
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011860 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 if (length == 1)
11862 return PyBool_FromLong(
11863 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011864
11865 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011866 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011867 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011868
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 for (i = 0; i < length; i++) {
11870 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011871 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011872 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011873 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011874}
11875
INADA Naoki3ae20562017-01-16 20:41:20 +090011876/*[clinic input]
11877str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011878
INADA Naoki3ae20562017-01-16 20:41:20 +090011879Return True if the string is an alpha-numeric string, False otherwise.
11880
11881A string is alpha-numeric if all characters in the string are alpha-numeric and
11882there is at least one character in the string.
11883[clinic start generated code]*/
11884
11885static PyObject *
11886unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011887/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 int kind;
11890 void *data;
11891 Py_ssize_t len, i;
11892
11893 if (PyUnicode_READY(self) == -1)
11894 return NULL;
11895
11896 kind = PyUnicode_KIND(self);
11897 data = PyUnicode_DATA(self);
11898 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011899
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011900 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 if (len == 1) {
11902 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11903 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11904 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011905
11906 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011908 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 for (i = 0; i < len; i++) {
11911 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011912 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011913 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011914 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011915 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011916}
11917
INADA Naoki3ae20562017-01-16 20:41:20 +090011918/*[clinic input]
11919str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920
INADA Naoki3ae20562017-01-16 20:41:20 +090011921Return True if the string is a decimal string, False otherwise.
11922
11923A string is a decimal string if all characters in the string are decimal and
11924there is at least one character in the string.
11925[clinic start generated code]*/
11926
11927static PyObject *
11928unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011929/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 Py_ssize_t i, length;
11932 int kind;
11933 void *data;
11934
11935 if (PyUnicode_READY(self) == -1)
11936 return NULL;
11937 length = PyUnicode_GET_LENGTH(self);
11938 kind = PyUnicode_KIND(self);
11939 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942 if (length == 1)
11943 return PyBool_FromLong(
11944 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011946 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011948 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 for (i = 0; i < length; i++) {
11951 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011952 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011954 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955}
11956
INADA Naoki3ae20562017-01-16 20:41:20 +090011957/*[clinic input]
11958str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959
INADA Naoki3ae20562017-01-16 20:41:20 +090011960Return True if the string is a digit string, False otherwise.
11961
11962A string is a digit string if all characters in the string are digits and there
11963is at least one character in the string.
11964[clinic start generated code]*/
11965
11966static PyObject *
11967unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011968/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 Py_ssize_t i, length;
11971 int kind;
11972 void *data;
11973
11974 if (PyUnicode_READY(self) == -1)
11975 return NULL;
11976 length = PyUnicode_GET_LENGTH(self);
11977 kind = PyUnicode_KIND(self);
11978 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 if (length == 1) {
11982 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11983 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11984 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011986 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011988 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 for (i = 0; i < length; i++) {
11991 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011992 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011994 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995}
11996
INADA Naoki3ae20562017-01-16 20:41:20 +090011997/*[clinic input]
11998str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000011999
INADA Naoki3ae20562017-01-16 20:41:20 +090012000Return True if the string is a numeric string, False otherwise.
12001
12002A string is numeric if all characters in the string are numeric and there is at
12003least one character in the string.
12004[clinic start generated code]*/
12005
12006static PyObject *
12007unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012008/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 Py_ssize_t i, length;
12011 int kind;
12012 void *data;
12013
12014 if (PyUnicode_READY(self) == -1)
12015 return NULL;
12016 length = PyUnicode_GET_LENGTH(self);
12017 kind = PyUnicode_KIND(self);
12018 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012019
Guido van Rossumd57fd912000-03-10 22:53:23 +000012020 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 if (length == 1)
12022 return PyBool_FromLong(
12023 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012025 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012027 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 for (i = 0; i < length; i++) {
12030 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012031 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012032 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012033 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012034}
12035
Martin v. Löwis47383402007-08-15 07:32:56 +000012036int
12037PyUnicode_IsIdentifier(PyObject *self)
12038{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039 int kind;
12040 void *data;
12041 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012042 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012043
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 if (PyUnicode_READY(self) == -1) {
12045 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012046 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 }
12048
12049 /* Special case for empty strings */
12050 if (PyUnicode_GET_LENGTH(self) == 0)
12051 return 0;
12052 kind = PyUnicode_KIND(self);
12053 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012054
12055 /* PEP 3131 says that the first character must be in
12056 XID_Start and subsequent characters in XID_Continue,
12057 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012058 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012059 letters, digits, underscore). However, given the current
12060 definition of XID_Start and XID_Continue, it is sufficient
12061 to check just for these, except that _ must be allowed
12062 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012063 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012064 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012065 return 0;
12066
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012067 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012069 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012070 return 1;
12071}
12072
INADA Naoki3ae20562017-01-16 20:41:20 +090012073/*[clinic input]
12074str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012075
INADA Naoki3ae20562017-01-16 20:41:20 +090012076Return True if the string is a valid Python identifier, False otherwise.
12077
12078Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12079"class".
12080[clinic start generated code]*/
12081
12082static PyObject *
12083unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012084/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012085{
12086 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12087}
12088
INADA Naoki3ae20562017-01-16 20:41:20 +090012089/*[clinic input]
12090str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012091
INADA Naoki3ae20562017-01-16 20:41:20 +090012092Return True if the string is printable, False otherwise.
12093
12094A string is printable if all of its characters are considered printable in
12095repr() or if it is empty.
12096[clinic start generated code]*/
12097
12098static PyObject *
12099unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012100/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012101{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 Py_ssize_t i, length;
12103 int kind;
12104 void *data;
12105
12106 if (PyUnicode_READY(self) == -1)
12107 return NULL;
12108 length = PyUnicode_GET_LENGTH(self);
12109 kind = PyUnicode_KIND(self);
12110 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012111
12112 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012113 if (length == 1)
12114 return PyBool_FromLong(
12115 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012117 for (i = 0; i < length; i++) {
12118 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012119 Py_RETURN_FALSE;
12120 }
12121 }
12122 Py_RETURN_TRUE;
12123}
12124
INADA Naoki3ae20562017-01-16 20:41:20 +090012125/*[clinic input]
12126str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127
INADA Naoki3ae20562017-01-16 20:41:20 +090012128 iterable: object
12129 /
12130
12131Concatenate any number of strings.
12132
Martin Panter91a88662017-01-24 00:30:06 +000012133The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012134The result is returned as a new string.
12135
12136Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12137[clinic start generated code]*/
12138
12139static PyObject *
12140unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012141/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142{
INADA Naoki3ae20562017-01-16 20:41:20 +090012143 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144}
12145
Martin v. Löwis18e16552006-02-15 17:27:45 +000012146static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012147unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149 if (PyUnicode_READY(self) == -1)
12150 return -1;
12151 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152}
12153
INADA Naoki3ae20562017-01-16 20:41:20 +090012154/*[clinic input]
12155str.ljust as unicode_ljust
12156
12157 width: Py_ssize_t
12158 fillchar: Py_UCS4 = ' '
12159 /
12160
12161Return a left-justified string of length width.
12162
12163Padding is done using the specified fill character (default is a space).
12164[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165
12166static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012167unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12168/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012170 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012171 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172
Victor Stinnerc4b49542011-12-11 22:44:26 +010012173 if (PyUnicode_GET_LENGTH(self) >= width)
12174 return unicode_result_unchanged(self);
12175
12176 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177}
12178
INADA Naoki3ae20562017-01-16 20:41:20 +090012179/*[clinic input]
12180str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
INADA Naoki3ae20562017-01-16 20:41:20 +090012182Return a copy of the string converted to lowercase.
12183[clinic start generated code]*/
12184
12185static PyObject *
12186unicode_lower_impl(PyObject *self)
12187/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012189 if (PyUnicode_READY(self) == -1)
12190 return NULL;
12191 if (PyUnicode_IS_ASCII(self))
12192 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012193 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194}
12195
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012196#define LEFTSTRIP 0
12197#define RIGHTSTRIP 1
12198#define BOTHSTRIP 2
12199
12200/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012201static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012202
INADA Naoki3ae20562017-01-16 20:41:20 +090012203#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012204
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012205/* externally visible for str.strip(unicode) */
12206PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012207_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012208{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 void *data;
12210 int kind;
12211 Py_ssize_t i, j, len;
12212 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012213 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012215 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12216 return NULL;
12217
12218 kind = PyUnicode_KIND(self);
12219 data = PyUnicode_DATA(self);
12220 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012221 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12223 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012224 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012225
Benjamin Peterson14339b62009-01-31 16:36:08 +000012226 i = 0;
12227 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012228 while (i < len) {
12229 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12230 if (!BLOOM(sepmask, ch))
12231 break;
12232 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12233 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012234 i++;
12235 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012236 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012237
Benjamin Peterson14339b62009-01-31 16:36:08 +000012238 j = len;
12239 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012240 j--;
12241 while (j >= i) {
12242 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12243 if (!BLOOM(sepmask, ch))
12244 break;
12245 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12246 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012247 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012248 }
12249
Benjamin Peterson29060642009-01-31 22:14:21 +000012250 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012251 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012252
Victor Stinner7931d9a2011-11-04 00:22:48 +010012253 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254}
12255
12256PyObject*
12257PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12258{
12259 unsigned char *data;
12260 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012261 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262
Victor Stinnerde636f32011-10-01 03:55:54 +020012263 if (PyUnicode_READY(self) == -1)
12264 return NULL;
12265
Victor Stinner684d5fd2012-05-03 02:32:34 +020012266 length = PyUnicode_GET_LENGTH(self);
12267 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012268
Victor Stinner684d5fd2012-05-03 02:32:34 +020012269 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012270 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012271
Victor Stinnerde636f32011-10-01 03:55:54 +020012272 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012273 PyErr_SetString(PyExc_IndexError, "string index out of range");
12274 return NULL;
12275 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012276 if (start >= length || end < start)
12277 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012278
Victor Stinner684d5fd2012-05-03 02:32:34 +020012279 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012280 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012281 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012282 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012283 }
12284 else {
12285 kind = PyUnicode_KIND(self);
12286 data = PyUnicode_1BYTE_DATA(self);
12287 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012288 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012289 length);
12290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012291}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292
12293static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012294do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 Py_ssize_t len, i, j;
12297
12298 if (PyUnicode_READY(self) == -1)
12299 return NULL;
12300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012302
Victor Stinnercc7af722013-04-09 22:39:24 +020012303 if (PyUnicode_IS_ASCII(self)) {
12304 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12305
12306 i = 0;
12307 if (striptype != RIGHTSTRIP) {
12308 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012309 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012310 if (!_Py_ascii_whitespace[ch])
12311 break;
12312 i++;
12313 }
12314 }
12315
12316 j = len;
12317 if (striptype != LEFTSTRIP) {
12318 j--;
12319 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012320 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012321 if (!_Py_ascii_whitespace[ch])
12322 break;
12323 j--;
12324 }
12325 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012326 }
12327 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012328 else {
12329 int kind = PyUnicode_KIND(self);
12330 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012331
Victor Stinnercc7af722013-04-09 22:39:24 +020012332 i = 0;
12333 if (striptype != RIGHTSTRIP) {
12334 while (i < len) {
12335 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12336 if (!Py_UNICODE_ISSPACE(ch))
12337 break;
12338 i++;
12339 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012340 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012341
12342 j = len;
12343 if (striptype != LEFTSTRIP) {
12344 j--;
12345 while (j >= i) {
12346 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12347 if (!Py_UNICODE_ISSPACE(ch))
12348 break;
12349 j--;
12350 }
12351 j++;
12352 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012353 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012354
Victor Stinner7931d9a2011-11-04 00:22:48 +010012355 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012356}
12357
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012358
12359static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012360do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012361{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012362 if (sep != NULL && sep != Py_None) {
12363 if (PyUnicode_Check(sep))
12364 return _PyUnicode_XStrip(self, striptype, sep);
12365 else {
12366 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012367 "%s arg must be None or str",
12368 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012369 return NULL;
12370 }
12371 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012372
Benjamin Peterson14339b62009-01-31 16:36:08 +000012373 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012374}
12375
12376
INADA Naoki3ae20562017-01-16 20:41:20 +090012377/*[clinic input]
12378str.strip as unicode_strip
12379
12380 chars: object = None
12381 /
12382
Victor Stinner0c4a8282017-01-17 02:21:47 +010012383Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012384
12385If chars is given and not None, remove characters in chars instead.
12386[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012387
12388static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012389unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012390/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012391{
INADA Naoki3ae20562017-01-16 20:41:20 +090012392 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012393}
12394
12395
INADA Naoki3ae20562017-01-16 20:41:20 +090012396/*[clinic input]
12397str.lstrip as unicode_lstrip
12398
12399 chars: object = NULL
12400 /
12401
12402Return a copy of the string with leading whitespace removed.
12403
12404If chars is given and not None, remove characters in chars instead.
12405[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012406
12407static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012408unicode_lstrip_impl(PyObject *self, PyObject *chars)
12409/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012410{
INADA Naoki3ae20562017-01-16 20:41:20 +090012411 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012412}
12413
12414
INADA Naoki3ae20562017-01-16 20:41:20 +090012415/*[clinic input]
12416str.rstrip as unicode_rstrip
12417
12418 chars: object = NULL
12419 /
12420
12421Return a copy of the string with trailing whitespace removed.
12422
12423If chars is given and not None, remove characters in chars instead.
12424[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012425
12426static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012427unicode_rstrip_impl(PyObject *self, PyObject *chars)
12428/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012429{
INADA Naoki3ae20562017-01-16 20:41:20 +090012430 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012431}
12432
12433
Guido van Rossumd57fd912000-03-10 22:53:23 +000012434static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012435unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012436{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012437 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012438 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012439
Serhiy Storchaka05997252013-01-26 12:14:02 +020012440 if (len < 1)
12441 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442
Victor Stinnerc4b49542011-12-11 22:44:26 +010012443 /* no repeat, return original string */
12444 if (len == 1)
12445 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012446
Benjamin Petersonbac79492012-01-14 13:34:47 -050012447 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 return NULL;
12449
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012450 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012451 PyErr_SetString(PyExc_OverflowError,
12452 "repeated string is too long");
12453 return NULL;
12454 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012455 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012456
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012457 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012458 if (!u)
12459 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012460 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 if (PyUnicode_GET_LENGTH(str) == 1) {
12463 const int kind = PyUnicode_KIND(str);
12464 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012465 if (kind == PyUnicode_1BYTE_KIND) {
12466 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012467 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012468 }
12469 else if (kind == PyUnicode_2BYTE_KIND) {
12470 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012471 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012472 ucs2[n] = fill_char;
12473 } else {
12474 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12475 assert(kind == PyUnicode_4BYTE_KIND);
12476 for (n = 0; n < len; ++n)
12477 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012479 }
12480 else {
12481 /* number of characters copied this far */
12482 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012483 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012484 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012485 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012487 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012489 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012490 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012491 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492 }
12493
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012494 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012495 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496}
12497
Alexander Belopolsky40018472011-02-26 01:02:56 +000012498PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012499PyUnicode_Replace(PyObject *str,
12500 PyObject *substr,
12501 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012502 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012504 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12505 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012506 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012507 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012508}
12509
INADA Naoki3ae20562017-01-16 20:41:20 +090012510/*[clinic input]
12511str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012512
INADA Naoki3ae20562017-01-16 20:41:20 +090012513 old: unicode
12514 new: unicode
12515 count: Py_ssize_t = -1
12516 Maximum number of occurrences to replace.
12517 -1 (the default value) means replace all occurrences.
12518 /
12519
12520Return a copy with all occurrences of substring old replaced by new.
12521
12522If the optional argument count is given, only the first count occurrences are
12523replaced.
12524[clinic start generated code]*/
12525
12526static PyObject *
12527unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12528 Py_ssize_t count)
12529/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012531 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012532 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012533 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534}
12535
Alexander Belopolsky40018472011-02-26 01:02:56 +000012536static PyObject *
12537unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012538{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012539 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012540 Py_ssize_t isize;
12541 Py_ssize_t osize, squote, dquote, i, o;
12542 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012543 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012547 return NULL;
12548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 isize = PyUnicode_GET_LENGTH(unicode);
12550 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 /* Compute length of output, quote characters, and
12553 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012554 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 max = 127;
12556 squote = dquote = 0;
12557 ikind = PyUnicode_KIND(unicode);
12558 for (i = 0; i < isize; i++) {
12559 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012560 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012562 case '\'': squote++; break;
12563 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012565 incr = 2;
12566 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 default:
12568 /* Fast-path ASCII */
12569 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012570 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012572 ;
12573 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012576 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012577 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012578 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012580 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012582 if (osize > PY_SSIZE_T_MAX - incr) {
12583 PyErr_SetString(PyExc_OverflowError,
12584 "string is too long to generate repr");
12585 return NULL;
12586 }
12587 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 }
12589
12590 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012591 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012593 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 if (dquote)
12595 /* Both squote and dquote present. Use squote,
12596 and escape them */
12597 osize += squote;
12598 else
12599 quote = '"';
12600 }
Victor Stinner55c08782013-04-14 18:45:39 +020012601 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012602
12603 repr = PyUnicode_New(osize, max);
12604 if (repr == NULL)
12605 return NULL;
12606 okind = PyUnicode_KIND(repr);
12607 odata = PyUnicode_DATA(repr);
12608
12609 PyUnicode_WRITE(okind, odata, 0, quote);
12610 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012611 if (unchanged) {
12612 _PyUnicode_FastCopyCharacters(repr, 1,
12613 unicode, 0,
12614 isize);
12615 }
12616 else {
12617 for (i = 0, o = 1; i < isize; i++) {
12618 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012619
Victor Stinner55c08782013-04-14 18:45:39 +020012620 /* Escape quotes and backslashes */
12621 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012622 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012624 continue;
12625 }
12626
12627 /* Map special whitespace to '\t', \n', '\r' */
12628 if (ch == '\t') {
12629 PyUnicode_WRITE(okind, odata, o++, '\\');
12630 PyUnicode_WRITE(okind, odata, o++, 't');
12631 }
12632 else if (ch == '\n') {
12633 PyUnicode_WRITE(okind, odata, o++, '\\');
12634 PyUnicode_WRITE(okind, odata, o++, 'n');
12635 }
12636 else if (ch == '\r') {
12637 PyUnicode_WRITE(okind, odata, o++, '\\');
12638 PyUnicode_WRITE(okind, odata, o++, 'r');
12639 }
12640
12641 /* Map non-printable US ASCII to '\xhh' */
12642 else if (ch < ' ' || ch == 0x7F) {
12643 PyUnicode_WRITE(okind, odata, o++, '\\');
12644 PyUnicode_WRITE(okind, odata, o++, 'x');
12645 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12646 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12647 }
12648
12649 /* Copy ASCII characters as-is */
12650 else if (ch < 0x7F) {
12651 PyUnicode_WRITE(okind, odata, o++, ch);
12652 }
12653
12654 /* Non-ASCII characters */
12655 else {
12656 /* Map Unicode whitespace and control characters
12657 (categories Z* and C* except ASCII space)
12658 */
12659 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12660 PyUnicode_WRITE(okind, odata, o++, '\\');
12661 /* Map 8-bit characters to '\xhh' */
12662 if (ch <= 0xff) {
12663 PyUnicode_WRITE(okind, odata, o++, 'x');
12664 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12665 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12666 }
12667 /* Map 16-bit characters to '\uxxxx' */
12668 else if (ch <= 0xffff) {
12669 PyUnicode_WRITE(okind, odata, o++, 'u');
12670 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12671 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12672 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12673 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12674 }
12675 /* Map 21-bit characters to '\U00xxxxxx' */
12676 else {
12677 PyUnicode_WRITE(okind, odata, o++, 'U');
12678 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12679 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12680 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12681 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12682 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12683 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12684 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12685 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12686 }
12687 }
12688 /* Copy characters as-is */
12689 else {
12690 PyUnicode_WRITE(okind, odata, o++, ch);
12691 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012692 }
12693 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012694 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012695 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012696 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012697 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698}
12699
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012700PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012701 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702\n\
12703Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012704such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705arguments start and end are interpreted as in slice notation.\n\
12706\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012707Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708
12709static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012712 /* initialize variables to prevent gcc warning */
12713 PyObject *substring = NULL;
12714 Py_ssize_t start = 0;
12715 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012716 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012718 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012721 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012724 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 if (result == -2)
12727 return NULL;
12728
Christian Heimes217cfd12007-12-02 14:31:20 +000012729 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012730}
12731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012732PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012735Return the highest index in S where substring sub is found,\n\
12736such that sub is contained within S[start:end]. Optional\n\
12737arguments start and end are interpreted as in slice notation.\n\
12738\n\
12739Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740
12741static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012744 /* initialize variables to prevent gcc warning */
12745 PyObject *substring = NULL;
12746 Py_ssize_t start = 0;
12747 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012748 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012750 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012751 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012753 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012754 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012755
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012756 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758 if (result == -2)
12759 return NULL;
12760
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761 if (result < 0) {
12762 PyErr_SetString(PyExc_ValueError, "substring not found");
12763 return NULL;
12764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765
Christian Heimes217cfd12007-12-02 14:31:20 +000012766 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767}
12768
INADA Naoki3ae20562017-01-16 20:41:20 +090012769/*[clinic input]
12770str.rjust as unicode_rjust
12771
12772 width: Py_ssize_t
12773 fillchar: Py_UCS4 = ' '
12774 /
12775
12776Return a right-justified string of length width.
12777
12778Padding is done using the specified fill character (default is a space).
12779[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780
12781static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012782unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12783/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012785 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786 return NULL;
12787
Victor Stinnerc4b49542011-12-11 22:44:26 +010012788 if (PyUnicode_GET_LENGTH(self) >= width)
12789 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790
Victor Stinnerc4b49542011-12-11 22:44:26 +010012791 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792}
12793
Alexander Belopolsky40018472011-02-26 01:02:56 +000012794PyObject *
12795PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012797 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012798 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012800 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801}
12802
INADA Naoki3ae20562017-01-16 20:41:20 +090012803/*[clinic input]
12804str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805
INADA Naoki3ae20562017-01-16 20:41:20 +090012806 sep: object = None
12807 The delimiter according which to split the string.
12808 None (the default value) means split according to any whitespace,
12809 and discard empty strings from the result.
12810 maxsplit: Py_ssize_t = -1
12811 Maximum number of splits to do.
12812 -1 (the default value) means no limit.
12813
12814Return a list of the words in the string, using sep as the delimiter string.
12815[clinic start generated code]*/
12816
12817static PyObject *
12818unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12819/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820{
INADA Naoki3ae20562017-01-16 20:41:20 +090012821 if (sep == Py_None)
12822 return split(self, NULL, maxsplit);
12823 if (PyUnicode_Check(sep))
12824 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012825
12826 PyErr_Format(PyExc_TypeError,
12827 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012828 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012829 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830}
12831
Thomas Wouters477c8d52006-05-27 19:21:47 +000012832PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012833PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012834{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012835 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012836 int kind1, kind2;
12837 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012838 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012839
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012840 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012841 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012842
Victor Stinner14f8f022011-10-05 20:58:25 +020012843 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012844 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012845 len1 = PyUnicode_GET_LENGTH(str_obj);
12846 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012847 if (kind1 < kind2 || len1 < len2) {
12848 _Py_INCREF_UNICODE_EMPTY();
12849 if (!unicode_empty)
12850 out = NULL;
12851 else {
12852 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12853 Py_DECREF(unicode_empty);
12854 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012855 return out;
12856 }
12857 buf1 = PyUnicode_DATA(str_obj);
12858 buf2 = PyUnicode_DATA(sep_obj);
12859 if (kind2 != kind1) {
12860 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12861 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012862 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012863 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012864
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012865 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012866 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012867 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12868 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12869 else
12870 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012871 break;
12872 case PyUnicode_2BYTE_KIND:
12873 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12874 break;
12875 case PyUnicode_4BYTE_KIND:
12876 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12877 break;
12878 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012879 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012880 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012881
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012882 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012883 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012884
12885 return out;
12886}
12887
12888
12889PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012890PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012891{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012892 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012893 int kind1, kind2;
12894 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012895 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012896
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012897 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012898 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012899
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012900 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012901 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 len1 = PyUnicode_GET_LENGTH(str_obj);
12903 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012904 if (kind1 < kind2 || len1 < len2) {
12905 _Py_INCREF_UNICODE_EMPTY();
12906 if (!unicode_empty)
12907 out = NULL;
12908 else {
12909 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12910 Py_DECREF(unicode_empty);
12911 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012912 return out;
12913 }
12914 buf1 = PyUnicode_DATA(str_obj);
12915 buf2 = PyUnicode_DATA(sep_obj);
12916 if (kind2 != kind1) {
12917 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12918 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012919 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012920 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012921
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012922 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012924 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12925 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12926 else
12927 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012928 break;
12929 case PyUnicode_2BYTE_KIND:
12930 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12931 break;
12932 case PyUnicode_4BYTE_KIND:
12933 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12934 break;
12935 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012936 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012937 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012938
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012939 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012940 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012941
12942 return out;
12943}
12944
INADA Naoki3ae20562017-01-16 20:41:20 +090012945/*[clinic input]
12946str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012947
INADA Naoki3ae20562017-01-16 20:41:20 +090012948 sep: object
12949 /
12950
12951Partition the string into three parts using the given separator.
12952
12953This will search for the separator in the string. If the separator is found,
12954returns a 3-tuple containing the part before the separator, the separator
12955itself, and the part after it.
12956
12957If the separator is not found, returns a 3-tuple containing the original string
12958and two empty strings.
12959[clinic start generated code]*/
12960
12961static PyObject *
12962unicode_partition(PyObject *self, PyObject *sep)
12963/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012964{
INADA Naoki3ae20562017-01-16 20:41:20 +090012965 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012966}
12967
INADA Naoki3ae20562017-01-16 20:41:20 +090012968/*[clinic input]
12969str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012970
INADA Naoki3ae20562017-01-16 20:41:20 +090012971Partition the string into three parts using the given separator.
12972
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012973This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012974the separator is found, returns a 3-tuple containing the part before the
12975separator, the separator itself, and the part after it.
12976
12977If the separator is not found, returns a 3-tuple containing two empty strings
12978and the original string.
12979[clinic start generated code]*/
12980
12981static PyObject *
12982unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012983/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012984{
INADA Naoki3ae20562017-01-16 20:41:20 +090012985 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012986}
12987
Alexander Belopolsky40018472011-02-26 01:02:56 +000012988PyObject *
12989PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012990{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012991 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012992 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012993
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012994 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012995}
12996
INADA Naoki3ae20562017-01-16 20:41:20 +090012997/*[clinic input]
12998str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012999
INADA Naoki3ae20562017-01-16 20:41:20 +090013000Return a list of the words in the string, using sep as the delimiter string.
13001
13002Splits are done starting at the end of the string and working to the front.
13003[clinic start generated code]*/
13004
13005static PyObject *
13006unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13007/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013008{
INADA Naoki3ae20562017-01-16 20:41:20 +090013009 if (sep == Py_None)
13010 return rsplit(self, NULL, maxsplit);
13011 if (PyUnicode_Check(sep))
13012 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013013
13014 PyErr_Format(PyExc_TypeError,
13015 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013016 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013017 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013018}
13019
INADA Naoki3ae20562017-01-16 20:41:20 +090013020/*[clinic input]
13021str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013022
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013023 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013024
13025Return a list of the lines in the string, breaking at line boundaries.
13026
13027Line breaks are not included in the resulting list unless keepends is given and
13028true.
13029[clinic start generated code]*/
13030
13031static PyObject *
13032unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013033/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013034{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013035 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013036}
13037
13038static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013039PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013041 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042}
13043
INADA Naoki3ae20562017-01-16 20:41:20 +090013044/*[clinic input]
13045str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013046
INADA Naoki3ae20562017-01-16 20:41:20 +090013047Convert uppercase characters to lowercase and lowercase characters to uppercase.
13048[clinic start generated code]*/
13049
13050static PyObject *
13051unicode_swapcase_impl(PyObject *self)
13052/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013053{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013054 if (PyUnicode_READY(self) == -1)
13055 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013056 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057}
13058
Larry Hastings61272b72014-01-07 12:41:53 -080013059/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013060
Larry Hastings31826802013-10-19 00:09:25 -070013061@staticmethod
13062str.maketrans as unicode_maketrans
13063
13064 x: object
13065
13066 y: unicode=NULL
13067
13068 z: unicode=NULL
13069
13070 /
13071
13072Return a translation table usable for str.translate().
13073
13074If there is only one argument, it must be a dictionary mapping Unicode
13075ordinals (integers) or characters to Unicode ordinals, strings or None.
13076Character keys will be then converted to ordinals.
13077If there are two arguments, they must be strings of equal length, and
13078in the resulting dictionary, each character in x will be mapped to the
13079character at the same position in y. If there is a third argument, it
13080must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013081[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013082
Larry Hastings31826802013-10-19 00:09:25 -070013083static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013084unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013085/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013086{
Georg Brandlceee0772007-11-27 23:48:05 +000013087 PyObject *new = NULL, *key, *value;
13088 Py_ssize_t i = 0;
13089 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013090
Georg Brandlceee0772007-11-27 23:48:05 +000013091 new = PyDict_New();
13092 if (!new)
13093 return NULL;
13094 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013095 int x_kind, y_kind, z_kind;
13096 void *x_data, *y_data, *z_data;
13097
Georg Brandlceee0772007-11-27 23:48:05 +000013098 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013099 if (!PyUnicode_Check(x)) {
13100 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13101 "be a string if there is a second argument");
13102 goto err;
13103 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013105 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13106 "arguments must have equal length");
13107 goto err;
13108 }
13109 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013110 x_kind = PyUnicode_KIND(x);
13111 y_kind = PyUnicode_KIND(y);
13112 x_data = PyUnicode_DATA(x);
13113 y_data = PyUnicode_DATA(y);
13114 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13115 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013116 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013117 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013118 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013119 if (!value) {
13120 Py_DECREF(key);
13121 goto err;
13122 }
Georg Brandlceee0772007-11-27 23:48:05 +000013123 res = PyDict_SetItem(new, key, value);
13124 Py_DECREF(key);
13125 Py_DECREF(value);
13126 if (res < 0)
13127 goto err;
13128 }
13129 /* create entries for deleting chars in z */
13130 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013131 z_kind = PyUnicode_KIND(z);
13132 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013133 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013134 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013135 if (!key)
13136 goto err;
13137 res = PyDict_SetItem(new, key, Py_None);
13138 Py_DECREF(key);
13139 if (res < 0)
13140 goto err;
13141 }
13142 }
13143 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 int kind;
13145 void *data;
13146
Georg Brandlceee0772007-11-27 23:48:05 +000013147 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013148 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013149 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13150 "to maketrans it must be a dict");
13151 goto err;
13152 }
13153 /* copy entries into the new dict, converting string keys to int keys */
13154 while (PyDict_Next(x, &i, &key, &value)) {
13155 if (PyUnicode_Check(key)) {
13156 /* convert string keys to integer keys */
13157 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013158 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013159 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13160 "table must be of length 1");
13161 goto err;
13162 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013163 kind = PyUnicode_KIND(key);
13164 data = PyUnicode_DATA(key);
13165 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013166 if (!newkey)
13167 goto err;
13168 res = PyDict_SetItem(new, newkey, value);
13169 Py_DECREF(newkey);
13170 if (res < 0)
13171 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013172 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013173 /* just keep integer keys */
13174 if (PyDict_SetItem(new, key, value) < 0)
13175 goto err;
13176 } else {
13177 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13178 "be strings or integers");
13179 goto err;
13180 }
13181 }
13182 }
13183 return new;
13184 err:
13185 Py_DECREF(new);
13186 return NULL;
13187}
13188
INADA Naoki3ae20562017-01-16 20:41:20 +090013189/*[clinic input]
13190str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191
INADA Naoki3ae20562017-01-16 20:41:20 +090013192 table: object
13193 Translation table, which must be a mapping of Unicode ordinals to
13194 Unicode ordinals, strings, or None.
13195 /
13196
13197Replace each character in the string using the given translation table.
13198
13199The table must implement lookup/indexing via __getitem__, for instance a
13200dictionary or list. If this operation raises LookupError, the character is
13201left untouched. Characters mapped to None are deleted.
13202[clinic start generated code]*/
13203
13204static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013205unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013206/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013208 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209}
13210
INADA Naoki3ae20562017-01-16 20:41:20 +090013211/*[clinic input]
13212str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213
INADA Naoki3ae20562017-01-16 20:41:20 +090013214Return a copy of the string converted to uppercase.
13215[clinic start generated code]*/
13216
13217static PyObject *
13218unicode_upper_impl(PyObject *self)
13219/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013221 if (PyUnicode_READY(self) == -1)
13222 return NULL;
13223 if (PyUnicode_IS_ASCII(self))
13224 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013225 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013226}
13227
INADA Naoki3ae20562017-01-16 20:41:20 +090013228/*[clinic input]
13229str.zfill as unicode_zfill
13230
13231 width: Py_ssize_t
13232 /
13233
13234Pad a numeric string with zeros on the left, to fill a field of the given width.
13235
13236The string is never truncated.
13237[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238
13239static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013240unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013241/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013243 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013244 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013245 int kind;
13246 void *data;
13247 Py_UCS4 chr;
13248
Benjamin Petersonbac79492012-01-14 13:34:47 -050013249 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013250 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251
Victor Stinnerc4b49542011-12-11 22:44:26 +010013252 if (PyUnicode_GET_LENGTH(self) >= width)
13253 return unicode_result_unchanged(self);
13254
13255 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256
13257 u = pad(self, fill, 0, '0');
13258
Walter Dörwald068325e2002-04-15 13:36:47 +000013259 if (u == NULL)
13260 return NULL;
13261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013262 kind = PyUnicode_KIND(u);
13263 data = PyUnicode_DATA(u);
13264 chr = PyUnicode_READ(kind, data, fill);
13265
13266 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013268 PyUnicode_WRITE(kind, data, 0, chr);
13269 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270 }
13271
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013272 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013273 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013274}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275
13276#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013277static PyObject *
13278unicode__decimal2ascii(PyObject *self)
13279{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013280 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013281}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013282#endif
13283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013284PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013285 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013286\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013287Return True if S starts with the specified prefix, False otherwise.\n\
13288With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013289With optional end, stop comparing S at that position.\n\
13290prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291
13292static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013293unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013295{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013296 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013297 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013298 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013299 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013300 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013301
Jesus Ceaac451502011-04-20 17:09:23 +020013302 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013303 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013304 if (PyTuple_Check(subobj)) {
13305 Py_ssize_t i;
13306 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013307 substring = PyTuple_GET_ITEM(subobj, i);
13308 if (!PyUnicode_Check(substring)) {
13309 PyErr_Format(PyExc_TypeError,
13310 "tuple for startswith must only contain str, "
13311 "not %.100s",
13312 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013313 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013314 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013315 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013316 if (result == -1)
13317 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013318 if (result) {
13319 Py_RETURN_TRUE;
13320 }
13321 }
13322 /* nothing matched */
13323 Py_RETURN_FALSE;
13324 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013325 if (!PyUnicode_Check(subobj)) {
13326 PyErr_Format(PyExc_TypeError,
13327 "startswith first arg must be str or "
13328 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013329 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013330 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013331 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013332 if (result == -1)
13333 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013334 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013335}
13336
13337
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013338PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013339 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013340\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013341Return True if S ends with the specified suffix, False otherwise.\n\
13342With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013343With optional end, stop comparing S at that position.\n\
13344suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345
13346static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013347unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013348 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013349{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013350 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013351 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013352 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013353 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013354 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013355
Jesus Ceaac451502011-04-20 17:09:23 +020013356 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013357 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013358 if (PyTuple_Check(subobj)) {
13359 Py_ssize_t i;
13360 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013361 substring = PyTuple_GET_ITEM(subobj, i);
13362 if (!PyUnicode_Check(substring)) {
13363 PyErr_Format(PyExc_TypeError,
13364 "tuple for endswith must only contain str, "
13365 "not %.100s",
13366 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013367 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013368 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013369 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013370 if (result == -1)
13371 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013372 if (result) {
13373 Py_RETURN_TRUE;
13374 }
13375 }
13376 Py_RETURN_FALSE;
13377 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013378 if (!PyUnicode_Check(subobj)) {
13379 PyErr_Format(PyExc_TypeError,
13380 "endswith first arg must be str or "
13381 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013382 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013383 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013384 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013385 if (result == -1)
13386 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013387 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388}
13389
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013390static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013391_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013392{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013393 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13394 writer->data = PyUnicode_DATA(writer->buffer);
13395
13396 if (!writer->readonly) {
13397 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013398 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013399 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013400 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013401 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13402 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13403 writer->kind = PyUnicode_WCHAR_KIND;
13404 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13405
Victor Stinner8f674cc2013-04-17 23:02:17 +020013406 /* Copy-on-write mode: set buffer size to 0 so
13407 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13408 * next write. */
13409 writer->size = 0;
13410 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013411}
13412
Victor Stinnerd3f08822012-05-29 12:57:52 +020013413void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013414_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013415{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013416 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013417
13418 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013419 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013420
13421 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13422 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13423 writer->kind = PyUnicode_WCHAR_KIND;
13424 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013425}
13426
Victor Stinnerd3f08822012-05-29 12:57:52 +020013427int
13428_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13429 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013430{
13431 Py_ssize_t newlen;
13432 PyObject *newbuffer;
13433
Victor Stinner2740e462016-09-06 16:58:36 -070013434 assert(maxchar <= MAX_UNICODE);
13435
Victor Stinnerca9381e2015-09-22 00:58:32 +020013436 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013437 assert((maxchar > writer->maxchar && length >= 0)
13438 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013439
Victor Stinner202fdca2012-05-07 12:47:02 +020013440 if (length > PY_SSIZE_T_MAX - writer->pos) {
13441 PyErr_NoMemory();
13442 return -1;
13443 }
13444 newlen = writer->pos + length;
13445
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013446 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013447
Victor Stinnerd3f08822012-05-29 12:57:52 +020013448 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013449 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013450 if (writer->overallocate
13451 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13452 /* overallocate to limit the number of realloc() */
13453 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013454 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013455 if (newlen < writer->min_length)
13456 newlen = writer->min_length;
13457
Victor Stinnerd3f08822012-05-29 12:57:52 +020013458 writer->buffer = PyUnicode_New(newlen, maxchar);
13459 if (writer->buffer == NULL)
13460 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013461 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013462 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013463 if (writer->overallocate
13464 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13465 /* overallocate to limit the number of realloc() */
13466 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013467 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013468 if (newlen < writer->min_length)
13469 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013470
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013471 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013472 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013473 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013474 newbuffer = PyUnicode_New(newlen, maxchar);
13475 if (newbuffer == NULL)
13476 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013477 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13478 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013479 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013480 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013481 }
13482 else {
13483 newbuffer = resize_compact(writer->buffer, newlen);
13484 if (newbuffer == NULL)
13485 return -1;
13486 }
13487 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013488 }
13489 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013490 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013491 newbuffer = PyUnicode_New(writer->size, maxchar);
13492 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013493 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013494 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13495 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013496 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013497 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013498 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013499 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013500
13501#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013502}
13503
Victor Stinnerca9381e2015-09-22 00:58:32 +020013504int
13505_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13506 enum PyUnicode_Kind kind)
13507{
13508 Py_UCS4 maxchar;
13509
13510 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13511 assert(writer->kind < kind);
13512
13513 switch (kind)
13514 {
13515 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13516 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13517 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13518 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013519 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013520 }
13521
13522 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13523}
13524
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013525static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013526_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013527{
Victor Stinner2740e462016-09-06 16:58:36 -070013528 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013529 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13530 return -1;
13531 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13532 writer->pos++;
13533 return 0;
13534}
13535
13536int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013537_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13538{
13539 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13540}
13541
13542int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013543_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13544{
13545 Py_UCS4 maxchar;
13546 Py_ssize_t len;
13547
13548 if (PyUnicode_READY(str) == -1)
13549 return -1;
13550 len = PyUnicode_GET_LENGTH(str);
13551 if (len == 0)
13552 return 0;
13553 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13554 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013555 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013556 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013557 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013558 Py_INCREF(str);
13559 writer->buffer = str;
13560 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013561 writer->pos += len;
13562 return 0;
13563 }
13564 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13565 return -1;
13566 }
13567 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13568 str, 0, len);
13569 writer->pos += len;
13570 return 0;
13571}
13572
Victor Stinnere215d962012-10-06 23:03:36 +020013573int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013574_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13575 Py_ssize_t start, Py_ssize_t end)
13576{
13577 Py_UCS4 maxchar;
13578 Py_ssize_t len;
13579
13580 if (PyUnicode_READY(str) == -1)
13581 return -1;
13582
13583 assert(0 <= start);
13584 assert(end <= PyUnicode_GET_LENGTH(str));
13585 assert(start <= end);
13586
13587 if (end == 0)
13588 return 0;
13589
13590 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13591 return _PyUnicodeWriter_WriteStr(writer, str);
13592
13593 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13594 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13595 else
13596 maxchar = writer->maxchar;
13597 len = end - start;
13598
13599 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13600 return -1;
13601
13602 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13603 str, start, len);
13604 writer->pos += len;
13605 return 0;
13606}
13607
13608int
Victor Stinner4a587072013-11-19 12:54:53 +010013609_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13610 const char *ascii, Py_ssize_t len)
13611{
13612 if (len == -1)
13613 len = strlen(ascii);
13614
13615 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13616
13617 if (writer->buffer == NULL && !writer->overallocate) {
13618 PyObject *str;
13619
13620 str = _PyUnicode_FromASCII(ascii, len);
13621 if (str == NULL)
13622 return -1;
13623
13624 writer->readonly = 1;
13625 writer->buffer = str;
13626 _PyUnicodeWriter_Update(writer);
13627 writer->pos += len;
13628 return 0;
13629 }
13630
13631 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13632 return -1;
13633
13634 switch (writer->kind)
13635 {
13636 case PyUnicode_1BYTE_KIND:
13637 {
13638 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13639 Py_UCS1 *data = writer->data;
13640
Christian Heimesf051e432016-09-13 20:22:02 +020013641 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013642 break;
13643 }
13644 case PyUnicode_2BYTE_KIND:
13645 {
13646 _PyUnicode_CONVERT_BYTES(
13647 Py_UCS1, Py_UCS2,
13648 ascii, ascii + len,
13649 (Py_UCS2 *)writer->data + writer->pos);
13650 break;
13651 }
13652 case PyUnicode_4BYTE_KIND:
13653 {
13654 _PyUnicode_CONVERT_BYTES(
13655 Py_UCS1, Py_UCS4,
13656 ascii, ascii + len,
13657 (Py_UCS4 *)writer->data + writer->pos);
13658 break;
13659 }
13660 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013661 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013662 }
13663
13664 writer->pos += len;
13665 return 0;
13666}
13667
13668int
13669_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13670 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013671{
13672 Py_UCS4 maxchar;
13673
13674 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13675 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13676 return -1;
13677 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13678 writer->pos += len;
13679 return 0;
13680}
13681
Victor Stinnerd3f08822012-05-29 12:57:52 +020013682PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013683_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013684{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013685 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013686
Victor Stinnerd3f08822012-05-29 12:57:52 +020013687 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013688 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013689 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013690 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013691
13692 str = writer->buffer;
13693 writer->buffer = NULL;
13694
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013695 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013696 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13697 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013698 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013699
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013700 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13701 PyObject *str2;
13702 str2 = resize_compact(str, writer->pos);
13703 if (str2 == NULL) {
13704 Py_DECREF(str);
13705 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013706 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013707 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013708 }
13709
Victor Stinner15a0bd32013-07-08 22:29:55 +020013710 assert(_PyUnicode_CheckConsistency(str, 1));
13711 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013712}
13713
Victor Stinnerd3f08822012-05-29 12:57:52 +020013714void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013715_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013716{
13717 Py_CLEAR(writer->buffer);
13718}
13719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013720#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013721
13722PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013723 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013724\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013725Return a formatted version of S, using substitutions from args and kwargs.\n\
13726The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013727
Eric Smith27bbca62010-11-04 17:06:58 +000013728PyDoc_STRVAR(format_map__doc__,
13729 "S.format_map(mapping) -> str\n\
13730\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013731Return a formatted version of S, using substitutions from mapping.\n\
13732The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013733
INADA Naoki3ae20562017-01-16 20:41:20 +090013734/*[clinic input]
13735str.__format__ as unicode___format__
13736
13737 format_spec: unicode
13738 /
13739
13740Return a formatted version of the string as described by format_spec.
13741[clinic start generated code]*/
13742
Eric Smith4a7d76d2008-05-30 18:10:19 +000013743static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013744unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013745/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013746{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013747 _PyUnicodeWriter writer;
13748 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013749
Victor Stinnerd3f08822012-05-29 12:57:52 +020013750 if (PyUnicode_READY(self) == -1)
13751 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013752 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013753 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13754 self, format_spec, 0,
13755 PyUnicode_GET_LENGTH(format_spec));
13756 if (ret == -1) {
13757 _PyUnicodeWriter_Dealloc(&writer);
13758 return NULL;
13759 }
13760 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013761}
13762
INADA Naoki3ae20562017-01-16 20:41:20 +090013763/*[clinic input]
13764str.__sizeof__ as unicode_sizeof
13765
13766Return the size of the string in memory, in bytes.
13767[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013768
13769static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013770unicode_sizeof_impl(PyObject *self)
13771/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013772{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013773 Py_ssize_t size;
13774
13775 /* If it's a compact object, account for base structure +
13776 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013777 if (PyUnicode_IS_COMPACT_ASCII(self))
13778 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13779 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013780 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013781 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013782 else {
13783 /* If it is a two-block object, account for base object, and
13784 for character block if present. */
13785 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013786 if (_PyUnicode_DATA_ANY(self))
13787 size += (PyUnicode_GET_LENGTH(self) + 1) *
13788 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013789 }
13790 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013791 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013792 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13793 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13794 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13795 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013796
13797 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013798}
13799
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013800static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013801unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013802{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013803 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013804 if (!copy)
13805 return NULL;
13806 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013807}
13808
Guido van Rossumd57fd912000-03-10 22:53:23 +000013809static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013810 UNICODE_ENCODE_METHODDEF
13811 UNICODE_REPLACE_METHODDEF
13812 UNICODE_SPLIT_METHODDEF
13813 UNICODE_RSPLIT_METHODDEF
13814 UNICODE_JOIN_METHODDEF
13815 UNICODE_CAPITALIZE_METHODDEF
13816 UNICODE_CASEFOLD_METHODDEF
13817 UNICODE_TITLE_METHODDEF
13818 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013819 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013820 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013821 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013822 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013823 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013824 UNICODE_LJUST_METHODDEF
13825 UNICODE_LOWER_METHODDEF
13826 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013827 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13828 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013829 UNICODE_RJUST_METHODDEF
13830 UNICODE_RSTRIP_METHODDEF
13831 UNICODE_RPARTITION_METHODDEF
13832 UNICODE_SPLITLINES_METHODDEF
13833 UNICODE_STRIP_METHODDEF
13834 UNICODE_SWAPCASE_METHODDEF
13835 UNICODE_TRANSLATE_METHODDEF
13836 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013837 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13838 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013839 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013840 UNICODE_ISLOWER_METHODDEF
13841 UNICODE_ISUPPER_METHODDEF
13842 UNICODE_ISTITLE_METHODDEF
13843 UNICODE_ISSPACE_METHODDEF
13844 UNICODE_ISDECIMAL_METHODDEF
13845 UNICODE_ISDIGIT_METHODDEF
13846 UNICODE_ISNUMERIC_METHODDEF
13847 UNICODE_ISALPHA_METHODDEF
13848 UNICODE_ISALNUM_METHODDEF
13849 UNICODE_ISIDENTIFIER_METHODDEF
13850 UNICODE_ISPRINTABLE_METHODDEF
13851 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013852 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013853 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013854 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013855 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013856 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013857#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013858 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013859 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013860#endif
13861
Benjamin Peterson14339b62009-01-31 16:36:08 +000013862 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013863 {NULL, NULL}
13864};
13865
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013866static PyObject *
13867unicode_mod(PyObject *v, PyObject *w)
13868{
Brian Curtindfc80e32011-08-10 20:28:54 -050013869 if (!PyUnicode_Check(v))
13870 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013871 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013872}
13873
13874static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013875 0, /*nb_add*/
13876 0, /*nb_subtract*/
13877 0, /*nb_multiply*/
13878 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013879};
13880
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013882 (lenfunc) unicode_length, /* sq_length */
13883 PyUnicode_Concat, /* sq_concat */
13884 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13885 (ssizeargfunc) unicode_getitem, /* sq_item */
13886 0, /* sq_slice */
13887 0, /* sq_ass_item */
13888 0, /* sq_ass_slice */
13889 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013890};
13891
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013892static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013893unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013894{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013895 if (PyUnicode_READY(self) == -1)
13896 return NULL;
13897
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013898 if (PyIndex_Check(item)) {
13899 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013900 if (i == -1 && PyErr_Occurred())
13901 return NULL;
13902 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013904 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013905 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013906 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013907 PyObject *result;
13908 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013909 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013910 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013911
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013912 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013913 return NULL;
13914 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013915 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13916 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013917
13918 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013919 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013920 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013921 slicelength == PyUnicode_GET_LENGTH(self)) {
13922 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013923 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013924 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013925 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013926 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013927 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013928 src_kind = PyUnicode_KIND(self);
13929 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013930 if (!PyUnicode_IS_ASCII(self)) {
13931 kind_limit = kind_maxchar_limit(src_kind);
13932 max_char = 0;
13933 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13934 ch = PyUnicode_READ(src_kind, src_data, cur);
13935 if (ch > max_char) {
13936 max_char = ch;
13937 if (max_char >= kind_limit)
13938 break;
13939 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013940 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013941 }
Victor Stinner55c99112011-10-13 01:17:06 +020013942 else
13943 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013944 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013945 if (result == NULL)
13946 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013947 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013948 dest_data = PyUnicode_DATA(result);
13949
13950 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013951 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13952 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013953 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013954 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013955 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013956 } else {
13957 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13958 return NULL;
13959 }
13960}
13961
13962static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013963 (lenfunc)unicode_length, /* mp_length */
13964 (binaryfunc)unicode_subscript, /* mp_subscript */
13965 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013966};
13967
Guido van Rossumd57fd912000-03-10 22:53:23 +000013968
Guido van Rossumd57fd912000-03-10 22:53:23 +000013969/* Helpers for PyUnicode_Format() */
13970
Victor Stinnera47082312012-10-04 02:19:54 +020013971struct unicode_formatter_t {
13972 PyObject *args;
13973 int args_owned;
13974 Py_ssize_t arglen, argidx;
13975 PyObject *dict;
13976
13977 enum PyUnicode_Kind fmtkind;
13978 Py_ssize_t fmtcnt, fmtpos;
13979 void *fmtdata;
13980 PyObject *fmtstr;
13981
13982 _PyUnicodeWriter writer;
13983};
13984
13985struct unicode_format_arg_t {
13986 Py_UCS4 ch;
13987 int flags;
13988 Py_ssize_t width;
13989 int prec;
13990 int sign;
13991};
13992
Guido van Rossumd57fd912000-03-10 22:53:23 +000013993static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013994unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013995{
Victor Stinnera47082312012-10-04 02:19:54 +020013996 Py_ssize_t argidx = ctx->argidx;
13997
13998 if (argidx < ctx->arglen) {
13999 ctx->argidx++;
14000 if (ctx->arglen < 0)
14001 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014002 else
Victor Stinnera47082312012-10-04 02:19:54 +020014003 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014004 }
14005 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014006 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014007 return NULL;
14008}
14009
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014010/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014011
Victor Stinnera47082312012-10-04 02:19:54 +020014012/* Format a float into the writer if the writer is not NULL, or into *p_output
14013 otherwise.
14014
14015 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014016static int
Victor Stinnera47082312012-10-04 02:19:54 +020014017formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14018 PyObject **p_output,
14019 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014020{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014021 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014022 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014023 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014024 int prec;
14025 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014026
Guido van Rossumd57fd912000-03-10 22:53:23 +000014027 x = PyFloat_AsDouble(v);
14028 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014029 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014030
Victor Stinnera47082312012-10-04 02:19:54 +020014031 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014032 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014033 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014034
Victor Stinnera47082312012-10-04 02:19:54 +020014035 if (arg->flags & F_ALT)
14036 dtoa_flags = Py_DTSF_ALT;
14037 else
14038 dtoa_flags = 0;
14039 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014040 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014041 return -1;
14042 len = strlen(p);
14043 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014044 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014045 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014046 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014047 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014048 }
14049 else
14050 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014051 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014052 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014053}
14054
Victor Stinnerd0880d52012-04-27 23:40:13 +020014055/* formatlong() emulates the format codes d, u, o, x and X, and
14056 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14057 * Python's regular ints.
14058 * Return value: a new PyUnicodeObject*, or NULL if error.
14059 * The output string is of the form
14060 * "-"? ("0x" | "0X")? digit+
14061 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14062 * set in flags. The case of hex digits will be correct,
14063 * There will be at least prec digits, zero-filled on the left if
14064 * necessary to get that many.
14065 * val object to be converted
14066 * flags bitmask of format flags; only F_ALT is looked at
14067 * prec minimum number of digits; 0-fill on left if needed
14068 * type a character in [duoxX]; u acts the same as d
14069 *
14070 * CAUTION: o, x and X conversions on regular ints can never
14071 * produce a '-' sign, but can for Python's unbounded ints.
14072 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014073PyObject *
14074_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014075{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014076 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014077 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014078 Py_ssize_t i;
14079 int sign; /* 1 if '-', else 0 */
14080 int len; /* number of characters */
14081 Py_ssize_t llen;
14082 int numdigits; /* len == numnondigits + numdigits */
14083 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014084
Victor Stinnerd0880d52012-04-27 23:40:13 +020014085 /* Avoid exceeding SSIZE_T_MAX */
14086 if (prec > INT_MAX-3) {
14087 PyErr_SetString(PyExc_OverflowError,
14088 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014089 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014090 }
14091
14092 assert(PyLong_Check(val));
14093
14094 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014095 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014096 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014097 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014098 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014099 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014100 /* int and int subclasses should print numerically when a numeric */
14101 /* format code is used (see issue18780) */
14102 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014103 break;
14104 case 'o':
14105 numnondigits = 2;
14106 result = PyNumber_ToBase(val, 8);
14107 break;
14108 case 'x':
14109 case 'X':
14110 numnondigits = 2;
14111 result = PyNumber_ToBase(val, 16);
14112 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014113 }
14114 if (!result)
14115 return NULL;
14116
14117 assert(unicode_modifiable(result));
14118 assert(PyUnicode_IS_READY(result));
14119 assert(PyUnicode_IS_ASCII(result));
14120
14121 /* To modify the string in-place, there can only be one reference. */
14122 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014123 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014124 PyErr_BadInternalCall();
14125 return NULL;
14126 }
14127 buf = PyUnicode_DATA(result);
14128 llen = PyUnicode_GET_LENGTH(result);
14129 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014130 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014131 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014132 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014133 return NULL;
14134 }
14135 len = (int)llen;
14136 sign = buf[0] == '-';
14137 numnondigits += sign;
14138 numdigits = len - numnondigits;
14139 assert(numdigits > 0);
14140
14141 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014142 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014143 (type == 'o' || type == 'x' || type == 'X'))) {
14144 assert(buf[sign] == '0');
14145 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14146 buf[sign+1] == 'o');
14147 numnondigits -= 2;
14148 buf += 2;
14149 len -= 2;
14150 if (sign)
14151 buf[0] = '-';
14152 assert(len == numnondigits + numdigits);
14153 assert(numdigits > 0);
14154 }
14155
14156 /* Fill with leading zeroes to meet minimum width. */
14157 if (prec > numdigits) {
14158 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14159 numnondigits + prec);
14160 char *b1;
14161 if (!r1) {
14162 Py_DECREF(result);
14163 return NULL;
14164 }
14165 b1 = PyBytes_AS_STRING(r1);
14166 for (i = 0; i < numnondigits; ++i)
14167 *b1++ = *buf++;
14168 for (i = 0; i < prec - numdigits; i++)
14169 *b1++ = '0';
14170 for (i = 0; i < numdigits; i++)
14171 *b1++ = *buf++;
14172 *b1 = '\0';
14173 Py_DECREF(result);
14174 result = r1;
14175 buf = PyBytes_AS_STRING(result);
14176 len = numnondigits + prec;
14177 }
14178
14179 /* Fix up case for hex conversions. */
14180 if (type == 'X') {
14181 /* Need to convert all lower case letters to upper case.
14182 and need to convert 0x to 0X (and -0x to -0X). */
14183 for (i = 0; i < len; i++)
14184 if (buf[i] >= 'a' && buf[i] <= 'x')
14185 buf[i] -= 'a'-'A';
14186 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014187 if (!PyUnicode_Check(result)
14188 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014189 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014190 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014191 Py_DECREF(result);
14192 result = unicode;
14193 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014194 else if (len != PyUnicode_GET_LENGTH(result)) {
14195 if (PyUnicode_Resize(&result, len) < 0)
14196 Py_CLEAR(result);
14197 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014198 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014199}
14200
Ethan Furmandf3ed242014-01-05 06:50:30 -080014201/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014202 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014203 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014204 * -1 and raise an exception on error */
14205static int
Victor Stinnera47082312012-10-04 02:19:54 +020014206mainformatlong(PyObject *v,
14207 struct unicode_format_arg_t *arg,
14208 PyObject **p_output,
14209 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014210{
14211 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014212 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014213
14214 if (!PyNumber_Check(v))
14215 goto wrongtype;
14216
Ethan Furman9ab74802014-03-21 06:38:46 -070014217 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014218 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014219 if (type == 'o' || type == 'x' || type == 'X') {
14220 iobj = PyNumber_Index(v);
14221 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014222 if (PyErr_ExceptionMatches(PyExc_TypeError))
14223 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014224 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014225 }
14226 }
14227 else {
14228 iobj = PyNumber_Long(v);
14229 if (iobj == NULL ) {
14230 if (PyErr_ExceptionMatches(PyExc_TypeError))
14231 goto wrongtype;
14232 return -1;
14233 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014234 }
14235 assert(PyLong_Check(iobj));
14236 }
14237 else {
14238 iobj = v;
14239 Py_INCREF(iobj);
14240 }
14241
14242 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014243 && arg->width == -1 && arg->prec == -1
14244 && !(arg->flags & (F_SIGN | F_BLANK))
14245 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014246 {
14247 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014248 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014249 int base;
14250
Victor Stinnera47082312012-10-04 02:19:54 +020014251 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014252 {
14253 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014254 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014255 case 'd':
14256 case 'i':
14257 case 'u':
14258 base = 10;
14259 break;
14260 case 'o':
14261 base = 8;
14262 break;
14263 case 'x':
14264 case 'X':
14265 base = 16;
14266 break;
14267 }
14268
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014269 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14270 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014271 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014272 }
14273 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014274 return 1;
14275 }
14276
Ethan Furmanb95b5612015-01-23 20:05:18 -080014277 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014278 Py_DECREF(iobj);
14279 if (res == NULL)
14280 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014281 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014282 return 0;
14283
14284wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014285 switch(type)
14286 {
14287 case 'o':
14288 case 'x':
14289 case 'X':
14290 PyErr_Format(PyExc_TypeError,
14291 "%%%c format: an integer is required, "
14292 "not %.200s",
14293 type, Py_TYPE(v)->tp_name);
14294 break;
14295 default:
14296 PyErr_Format(PyExc_TypeError,
14297 "%%%c format: a number is required, "
14298 "not %.200s",
14299 type, Py_TYPE(v)->tp_name);
14300 break;
14301 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014302 return -1;
14303}
14304
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014305static Py_UCS4
14306formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014307{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014308 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014309 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014310 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014311 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014312 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014313 goto onError;
14314 }
14315 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014316 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014317 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014318 /* make sure number is a type of integer */
14319 if (!PyLong_Check(v)) {
14320 iobj = PyNumber_Index(v);
14321 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014322 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014323 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014324 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014325 Py_DECREF(iobj);
14326 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014327 else {
14328 x = PyLong_AsLong(v);
14329 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014330 if (x == -1 && PyErr_Occurred())
14331 goto onError;
14332
Victor Stinner8faf8212011-12-08 22:14:11 +010014333 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014334 PyErr_SetString(PyExc_OverflowError,
14335 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014336 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014337 }
14338
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014339 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014340 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014341
Benjamin Peterson29060642009-01-31 22:14:21 +000014342 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014343 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014344 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014345 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014346}
14347
Victor Stinnera47082312012-10-04 02:19:54 +020014348/* Parse options of an argument: flags, width, precision.
14349 Handle also "%(name)" syntax.
14350
14351 Return 0 if the argument has been formatted into arg->str.
14352 Return 1 if the argument has been written into ctx->writer,
14353 Raise an exception and return -1 on error. */
14354static int
14355unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14356 struct unicode_format_arg_t *arg)
14357{
14358#define FORMAT_READ(ctx) \
14359 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14360
14361 PyObject *v;
14362
Victor Stinnera47082312012-10-04 02:19:54 +020014363 if (arg->ch == '(') {
14364 /* Get argument value from a dictionary. Example: "%(name)s". */
14365 Py_ssize_t keystart;
14366 Py_ssize_t keylen;
14367 PyObject *key;
14368 int pcount = 1;
14369
14370 if (ctx->dict == NULL) {
14371 PyErr_SetString(PyExc_TypeError,
14372 "format requires a mapping");
14373 return -1;
14374 }
14375 ++ctx->fmtpos;
14376 --ctx->fmtcnt;
14377 keystart = ctx->fmtpos;
14378 /* Skip over balanced parentheses */
14379 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14380 arg->ch = FORMAT_READ(ctx);
14381 if (arg->ch == ')')
14382 --pcount;
14383 else if (arg->ch == '(')
14384 ++pcount;
14385 ctx->fmtpos++;
14386 }
14387 keylen = ctx->fmtpos - keystart - 1;
14388 if (ctx->fmtcnt < 0 || pcount > 0) {
14389 PyErr_SetString(PyExc_ValueError,
14390 "incomplete format key");
14391 return -1;
14392 }
14393 key = PyUnicode_Substring(ctx->fmtstr,
14394 keystart, keystart + keylen);
14395 if (key == NULL)
14396 return -1;
14397 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014398 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014399 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014400 }
14401 ctx->args = PyObject_GetItem(ctx->dict, key);
14402 Py_DECREF(key);
14403 if (ctx->args == NULL)
14404 return -1;
14405 ctx->args_owned = 1;
14406 ctx->arglen = -1;
14407 ctx->argidx = -2;
14408 }
14409
14410 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014411 while (--ctx->fmtcnt >= 0) {
14412 arg->ch = FORMAT_READ(ctx);
14413 ctx->fmtpos++;
14414 switch (arg->ch) {
14415 case '-': arg->flags |= F_LJUST; continue;
14416 case '+': arg->flags |= F_SIGN; continue;
14417 case ' ': arg->flags |= F_BLANK; continue;
14418 case '#': arg->flags |= F_ALT; continue;
14419 case '0': arg->flags |= F_ZERO; continue;
14420 }
14421 break;
14422 }
14423
14424 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014425 if (arg->ch == '*') {
14426 v = unicode_format_getnextarg(ctx);
14427 if (v == NULL)
14428 return -1;
14429 if (!PyLong_Check(v)) {
14430 PyErr_SetString(PyExc_TypeError,
14431 "* wants int");
14432 return -1;
14433 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014434 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014435 if (arg->width == -1 && PyErr_Occurred())
14436 return -1;
14437 if (arg->width < 0) {
14438 arg->flags |= F_LJUST;
14439 arg->width = -arg->width;
14440 }
14441 if (--ctx->fmtcnt >= 0) {
14442 arg->ch = FORMAT_READ(ctx);
14443 ctx->fmtpos++;
14444 }
14445 }
14446 else if (arg->ch >= '0' && arg->ch <= '9') {
14447 arg->width = arg->ch - '0';
14448 while (--ctx->fmtcnt >= 0) {
14449 arg->ch = FORMAT_READ(ctx);
14450 ctx->fmtpos++;
14451 if (arg->ch < '0' || arg->ch > '9')
14452 break;
14453 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14454 mixing signed and unsigned comparison. Since arg->ch is between
14455 '0' and '9', casting to int is safe. */
14456 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14457 PyErr_SetString(PyExc_ValueError,
14458 "width too big");
14459 return -1;
14460 }
14461 arg->width = arg->width*10 + (arg->ch - '0');
14462 }
14463 }
14464
14465 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014466 if (arg->ch == '.') {
14467 arg->prec = 0;
14468 if (--ctx->fmtcnt >= 0) {
14469 arg->ch = FORMAT_READ(ctx);
14470 ctx->fmtpos++;
14471 }
14472 if (arg->ch == '*') {
14473 v = unicode_format_getnextarg(ctx);
14474 if (v == NULL)
14475 return -1;
14476 if (!PyLong_Check(v)) {
14477 PyErr_SetString(PyExc_TypeError,
14478 "* wants int");
14479 return -1;
14480 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014481 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014482 if (arg->prec == -1 && PyErr_Occurred())
14483 return -1;
14484 if (arg->prec < 0)
14485 arg->prec = 0;
14486 if (--ctx->fmtcnt >= 0) {
14487 arg->ch = FORMAT_READ(ctx);
14488 ctx->fmtpos++;
14489 }
14490 }
14491 else if (arg->ch >= '0' && arg->ch <= '9') {
14492 arg->prec = arg->ch - '0';
14493 while (--ctx->fmtcnt >= 0) {
14494 arg->ch = FORMAT_READ(ctx);
14495 ctx->fmtpos++;
14496 if (arg->ch < '0' || arg->ch > '9')
14497 break;
14498 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14499 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014500 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014501 return -1;
14502 }
14503 arg->prec = arg->prec*10 + (arg->ch - '0');
14504 }
14505 }
14506 }
14507
14508 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14509 if (ctx->fmtcnt >= 0) {
14510 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14511 if (--ctx->fmtcnt >= 0) {
14512 arg->ch = FORMAT_READ(ctx);
14513 ctx->fmtpos++;
14514 }
14515 }
14516 }
14517 if (ctx->fmtcnt < 0) {
14518 PyErr_SetString(PyExc_ValueError,
14519 "incomplete format");
14520 return -1;
14521 }
14522 return 0;
14523
14524#undef FORMAT_READ
14525}
14526
14527/* Format one argument. Supported conversion specifiers:
14528
14529 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014530 - "i", "d", "u": int or float
14531 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014532 - "e", "E", "f", "F", "g", "G": float
14533 - "c": int or str (1 character)
14534
Victor Stinner8dbd4212012-12-04 09:30:24 +010014535 When possible, the output is written directly into the Unicode writer
14536 (ctx->writer). A string is created when padding is required.
14537
Victor Stinnera47082312012-10-04 02:19:54 +020014538 Return 0 if the argument has been formatted into *p_str,
14539 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014540 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014541static int
14542unicode_format_arg_format(struct unicode_formatter_t *ctx,
14543 struct unicode_format_arg_t *arg,
14544 PyObject **p_str)
14545{
14546 PyObject *v;
14547 _PyUnicodeWriter *writer = &ctx->writer;
14548
14549 if (ctx->fmtcnt == 0)
14550 ctx->writer.overallocate = 0;
14551
Victor Stinnera47082312012-10-04 02:19:54 +020014552 v = unicode_format_getnextarg(ctx);
14553 if (v == NULL)
14554 return -1;
14555
Victor Stinnera47082312012-10-04 02:19:54 +020014556
14557 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014558 case 's':
14559 case 'r':
14560 case 'a':
14561 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14562 /* Fast path */
14563 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14564 return -1;
14565 return 1;
14566 }
14567
14568 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14569 *p_str = v;
14570 Py_INCREF(*p_str);
14571 }
14572 else {
14573 if (arg->ch == 's')
14574 *p_str = PyObject_Str(v);
14575 else if (arg->ch == 'r')
14576 *p_str = PyObject_Repr(v);
14577 else
14578 *p_str = PyObject_ASCII(v);
14579 }
14580 break;
14581
14582 case 'i':
14583 case 'd':
14584 case 'u':
14585 case 'o':
14586 case 'x':
14587 case 'X':
14588 {
14589 int ret = mainformatlong(v, arg, p_str, writer);
14590 if (ret != 0)
14591 return ret;
14592 arg->sign = 1;
14593 break;
14594 }
14595
14596 case 'e':
14597 case 'E':
14598 case 'f':
14599 case 'F':
14600 case 'g':
14601 case 'G':
14602 if (arg->width == -1 && arg->prec == -1
14603 && !(arg->flags & (F_SIGN | F_BLANK)))
14604 {
14605 /* Fast path */
14606 if (formatfloat(v, arg, NULL, writer) == -1)
14607 return -1;
14608 return 1;
14609 }
14610
14611 arg->sign = 1;
14612 if (formatfloat(v, arg, p_str, NULL) == -1)
14613 return -1;
14614 break;
14615
14616 case 'c':
14617 {
14618 Py_UCS4 ch = formatchar(v);
14619 if (ch == (Py_UCS4) -1)
14620 return -1;
14621 if (arg->width == -1 && arg->prec == -1) {
14622 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014623 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014624 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014625 return 1;
14626 }
14627 *p_str = PyUnicode_FromOrdinal(ch);
14628 break;
14629 }
14630
14631 default:
14632 PyErr_Format(PyExc_ValueError,
14633 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014634 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014635 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14636 (int)arg->ch,
14637 ctx->fmtpos - 1);
14638 return -1;
14639 }
14640 if (*p_str == NULL)
14641 return -1;
14642 assert (PyUnicode_Check(*p_str));
14643 return 0;
14644}
14645
14646static int
14647unicode_format_arg_output(struct unicode_formatter_t *ctx,
14648 struct unicode_format_arg_t *arg,
14649 PyObject *str)
14650{
14651 Py_ssize_t len;
14652 enum PyUnicode_Kind kind;
14653 void *pbuf;
14654 Py_ssize_t pindex;
14655 Py_UCS4 signchar;
14656 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014657 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014658 Py_ssize_t sublen;
14659 _PyUnicodeWriter *writer = &ctx->writer;
14660 Py_UCS4 fill;
14661
14662 fill = ' ';
14663 if (arg->sign && arg->flags & F_ZERO)
14664 fill = '0';
14665
14666 if (PyUnicode_READY(str) == -1)
14667 return -1;
14668
14669 len = PyUnicode_GET_LENGTH(str);
14670 if ((arg->width == -1 || arg->width <= len)
14671 && (arg->prec == -1 || arg->prec >= len)
14672 && !(arg->flags & (F_SIGN | F_BLANK)))
14673 {
14674 /* Fast path */
14675 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14676 return -1;
14677 return 0;
14678 }
14679
14680 /* Truncate the string for "s", "r" and "a" formats
14681 if the precision is set */
14682 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14683 if (arg->prec >= 0 && len > arg->prec)
14684 len = arg->prec;
14685 }
14686
14687 /* Adjust sign and width */
14688 kind = PyUnicode_KIND(str);
14689 pbuf = PyUnicode_DATA(str);
14690 pindex = 0;
14691 signchar = '\0';
14692 if (arg->sign) {
14693 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14694 if (ch == '-' || ch == '+') {
14695 signchar = ch;
14696 len--;
14697 pindex++;
14698 }
14699 else if (arg->flags & F_SIGN)
14700 signchar = '+';
14701 else if (arg->flags & F_BLANK)
14702 signchar = ' ';
14703 else
14704 arg->sign = 0;
14705 }
14706 if (arg->width < len)
14707 arg->width = len;
14708
14709 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014710 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014711 if (!(arg->flags & F_LJUST)) {
14712 if (arg->sign) {
14713 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014714 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014715 }
14716 else {
14717 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014718 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014719 }
14720 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014721 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14722 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014723 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014724 }
14725
Victor Stinnera47082312012-10-04 02:19:54 +020014726 buflen = arg->width;
14727 if (arg->sign && len == arg->width)
14728 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014729 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014730 return -1;
14731
14732 /* Write the sign if needed */
14733 if (arg->sign) {
14734 if (fill != ' ') {
14735 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14736 writer->pos += 1;
14737 }
14738 if (arg->width > len)
14739 arg->width--;
14740 }
14741
14742 /* Write the numeric prefix for "x", "X" and "o" formats
14743 if the alternate form is used.
14744 For example, write "0x" for the "%#x" format. */
14745 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14746 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14747 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14748 if (fill != ' ') {
14749 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14750 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14751 writer->pos += 2;
14752 pindex += 2;
14753 }
14754 arg->width -= 2;
14755 if (arg->width < 0)
14756 arg->width = 0;
14757 len -= 2;
14758 }
14759
14760 /* Pad left with the fill character if needed */
14761 if (arg->width > len && !(arg->flags & F_LJUST)) {
14762 sublen = arg->width - len;
14763 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14764 writer->pos += sublen;
14765 arg->width = len;
14766 }
14767
14768 /* If padding with spaces: write sign if needed and/or numeric prefix if
14769 the alternate form is used */
14770 if (fill == ' ') {
14771 if (arg->sign) {
14772 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14773 writer->pos += 1;
14774 }
14775 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14776 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14777 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14778 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14779 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14780 writer->pos += 2;
14781 pindex += 2;
14782 }
14783 }
14784
14785 /* Write characters */
14786 if (len) {
14787 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14788 str, pindex, len);
14789 writer->pos += len;
14790 }
14791
14792 /* Pad right with the fill character if needed */
14793 if (arg->width > len) {
14794 sublen = arg->width - len;
14795 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14796 writer->pos += sublen;
14797 }
14798 return 0;
14799}
14800
14801/* Helper of PyUnicode_Format(): format one arg.
14802 Return 0 on success, raise an exception and return -1 on error. */
14803static int
14804unicode_format_arg(struct unicode_formatter_t *ctx)
14805{
14806 struct unicode_format_arg_t arg;
14807 PyObject *str;
14808 int ret;
14809
Victor Stinner8dbd4212012-12-04 09:30:24 +010014810 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014811 if (arg.ch == '%') {
14812 ctx->fmtpos++;
14813 ctx->fmtcnt--;
14814 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14815 return -1;
14816 return 0;
14817 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014818 arg.flags = 0;
14819 arg.width = -1;
14820 arg.prec = -1;
14821 arg.sign = 0;
14822 str = NULL;
14823
Victor Stinnera47082312012-10-04 02:19:54 +020014824 ret = unicode_format_arg_parse(ctx, &arg);
14825 if (ret == -1)
14826 return -1;
14827
14828 ret = unicode_format_arg_format(ctx, &arg, &str);
14829 if (ret == -1)
14830 return -1;
14831
14832 if (ret != 1) {
14833 ret = unicode_format_arg_output(ctx, &arg, str);
14834 Py_DECREF(str);
14835 if (ret == -1)
14836 return -1;
14837 }
14838
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014839 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014840 PyErr_SetString(PyExc_TypeError,
14841 "not all arguments converted during string formatting");
14842 return -1;
14843 }
14844 return 0;
14845}
14846
Alexander Belopolsky40018472011-02-26 01:02:56 +000014847PyObject *
14848PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014849{
Victor Stinnera47082312012-10-04 02:19:54 +020014850 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014851
Guido van Rossumd57fd912000-03-10 22:53:23 +000014852 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014853 PyErr_BadInternalCall();
14854 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014855 }
Victor Stinnera47082312012-10-04 02:19:54 +020014856
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014857 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014858 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014859
14860 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014861 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14862 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14863 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14864 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014865
Victor Stinner8f674cc2013-04-17 23:02:17 +020014866 _PyUnicodeWriter_Init(&ctx.writer);
14867 ctx.writer.min_length = ctx.fmtcnt + 100;
14868 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014869
Guido van Rossumd57fd912000-03-10 22:53:23 +000014870 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014871 ctx.arglen = PyTuple_Size(args);
14872 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014873 }
14874 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014875 ctx.arglen = -1;
14876 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014877 }
Victor Stinnera47082312012-10-04 02:19:54 +020014878 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014879 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014880 ctx.dict = args;
14881 else
14882 ctx.dict = NULL;
14883 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014884
Victor Stinnera47082312012-10-04 02:19:54 +020014885 while (--ctx.fmtcnt >= 0) {
14886 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014887 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014888
14889 nonfmtpos = ctx.fmtpos++;
14890 while (ctx.fmtcnt >= 0 &&
14891 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14892 ctx.fmtpos++;
14893 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014894 }
Victor Stinnera47082312012-10-04 02:19:54 +020014895 if (ctx.fmtcnt < 0) {
14896 ctx.fmtpos--;
14897 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014898 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014899
Victor Stinnercfc4c132013-04-03 01:48:39 +020014900 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14901 nonfmtpos, ctx.fmtpos) < 0)
14902 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014903 }
14904 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014905 ctx.fmtpos++;
14906 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014907 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014908 }
14909 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014910
Victor Stinnera47082312012-10-04 02:19:54 +020014911 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014912 PyErr_SetString(PyExc_TypeError,
14913 "not all arguments converted during string formatting");
14914 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014915 }
14916
Victor Stinnera47082312012-10-04 02:19:54 +020014917 if (ctx.args_owned) {
14918 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014919 }
Victor Stinnera47082312012-10-04 02:19:54 +020014920 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014921
Benjamin Peterson29060642009-01-31 22:14:21 +000014922 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014923 _PyUnicodeWriter_Dealloc(&ctx.writer);
14924 if (ctx.args_owned) {
14925 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014926 }
14927 return NULL;
14928}
14929
Jeremy Hylton938ace62002-07-17 16:30:39 +000014930static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014931unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14932
Tim Peters6d6c1a32001-08-02 04:15:00 +000014933static PyObject *
14934unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14935{
Benjamin Peterson29060642009-01-31 22:14:21 +000014936 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014937 static char *kwlist[] = {"object", "encoding", "errors", 0};
14938 char *encoding = NULL;
14939 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014940
Benjamin Peterson14339b62009-01-31 16:36:08 +000014941 if (type != &PyUnicode_Type)
14942 return unicode_subtype_new(type, args, kwds);
14943 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014944 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014945 return NULL;
14946 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014947 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014948 if (encoding == NULL && errors == NULL)
14949 return PyObject_Str(x);
14950 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014951 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014952}
14953
Guido van Rossume023fe02001-08-30 03:12:59 +000014954static PyObject *
14955unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14956{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014957 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014958 Py_ssize_t length, char_size;
14959 int share_wstr, share_utf8;
14960 unsigned int kind;
14961 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014962
Benjamin Peterson14339b62009-01-31 16:36:08 +000014963 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014964
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014965 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014966 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014967 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014968 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014969 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014970 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014971 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014972 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014973
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014974 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014975 if (self == NULL) {
14976 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014977 return NULL;
14978 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014979 kind = PyUnicode_KIND(unicode);
14980 length = PyUnicode_GET_LENGTH(unicode);
14981
14982 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014983#ifdef Py_DEBUG
14984 _PyUnicode_HASH(self) = -1;
14985#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014986 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014987#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014988 _PyUnicode_STATE(self).interned = 0;
14989 _PyUnicode_STATE(self).kind = kind;
14990 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014991 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014992 _PyUnicode_STATE(self).ready = 1;
14993 _PyUnicode_WSTR(self) = NULL;
14994 _PyUnicode_UTF8_LENGTH(self) = 0;
14995 _PyUnicode_UTF8(self) = NULL;
14996 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014997 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014998
14999 share_utf8 = 0;
15000 share_wstr = 0;
15001 if (kind == PyUnicode_1BYTE_KIND) {
15002 char_size = 1;
15003 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15004 share_utf8 = 1;
15005 }
15006 else if (kind == PyUnicode_2BYTE_KIND) {
15007 char_size = 2;
15008 if (sizeof(wchar_t) == 2)
15009 share_wstr = 1;
15010 }
15011 else {
15012 assert(kind == PyUnicode_4BYTE_KIND);
15013 char_size = 4;
15014 if (sizeof(wchar_t) == 4)
15015 share_wstr = 1;
15016 }
15017
15018 /* Ensure we won't overflow the length. */
15019 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15020 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015021 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015022 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015023 data = PyObject_MALLOC((length + 1) * char_size);
15024 if (data == NULL) {
15025 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015026 goto onError;
15027 }
15028
Victor Stinnerc3c74152011-10-02 20:39:55 +020015029 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015030 if (share_utf8) {
15031 _PyUnicode_UTF8_LENGTH(self) = length;
15032 _PyUnicode_UTF8(self) = data;
15033 }
15034 if (share_wstr) {
15035 _PyUnicode_WSTR_LENGTH(self) = length;
15036 _PyUnicode_WSTR(self) = (wchar_t *)data;
15037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015038
Christian Heimesf051e432016-09-13 20:22:02 +020015039 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015040 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015041 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015042#ifdef Py_DEBUG
15043 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15044#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015045 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015046 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015047
15048onError:
15049 Py_DECREF(unicode);
15050 Py_DECREF(self);
15051 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015052}
15053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015054PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015055"str(object='') -> str\n\
15056str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015057\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015058Create a new string object from the given object. If encoding or\n\
15059errors is specified, then the object must expose a data buffer\n\
15060that will be decoded using the given encoding and error handler.\n\
15061Otherwise, returns the result of object.__str__() (if defined)\n\
15062or repr(object).\n\
15063encoding defaults to sys.getdefaultencoding().\n\
15064errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015065
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015066static PyObject *unicode_iter(PyObject *seq);
15067
Guido van Rossumd57fd912000-03-10 22:53:23 +000015068PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015069 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015070 "str", /* tp_name */
15071 sizeof(PyUnicodeObject), /* tp_size */
15072 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015073 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015074 (destructor)unicode_dealloc, /* tp_dealloc */
15075 0, /* tp_print */
15076 0, /* tp_getattr */
15077 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015078 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015079 unicode_repr, /* tp_repr */
15080 &unicode_as_number, /* tp_as_number */
15081 &unicode_as_sequence, /* tp_as_sequence */
15082 &unicode_as_mapping, /* tp_as_mapping */
15083 (hashfunc) unicode_hash, /* tp_hash*/
15084 0, /* tp_call*/
15085 (reprfunc) unicode_str, /* tp_str */
15086 PyObject_GenericGetAttr, /* tp_getattro */
15087 0, /* tp_setattro */
15088 0, /* tp_as_buffer */
15089 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015090 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015091 unicode_doc, /* tp_doc */
15092 0, /* tp_traverse */
15093 0, /* tp_clear */
15094 PyUnicode_RichCompare, /* tp_richcompare */
15095 0, /* tp_weaklistoffset */
15096 unicode_iter, /* tp_iter */
15097 0, /* tp_iternext */
15098 unicode_methods, /* tp_methods */
15099 0, /* tp_members */
15100 0, /* tp_getset */
15101 &PyBaseObject_Type, /* tp_base */
15102 0, /* tp_dict */
15103 0, /* tp_descr_get */
15104 0, /* tp_descr_set */
15105 0, /* tp_dictoffset */
15106 0, /* tp_init */
15107 0, /* tp_alloc */
15108 unicode_new, /* tp_new */
15109 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015110};
15111
15112/* Initialize the Unicode implementation */
15113
Victor Stinner3a50e702011-10-18 21:21:00 +020015114int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015115{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015116 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015117 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015118 0x000A, /* LINE FEED */
15119 0x000D, /* CARRIAGE RETURN */
15120 0x001C, /* FILE SEPARATOR */
15121 0x001D, /* GROUP SEPARATOR */
15122 0x001E, /* RECORD SEPARATOR */
15123 0x0085, /* NEXT LINE */
15124 0x2028, /* LINE SEPARATOR */
15125 0x2029, /* PARAGRAPH SEPARATOR */
15126 };
15127
Fred Drakee4315f52000-05-09 19:53:39 +000015128 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015129 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015130 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015131 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015132 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015133
Guido van Rossumcacfc072002-05-24 19:01:59 +000015134 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015135 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015136
15137 /* initialize the linebreak bloom filter */
15138 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015139 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015140 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015141
Christian Heimes26532f72013-07-20 14:57:16 +020015142 if (PyType_Ready(&EncodingMapType) < 0)
15143 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015144
Benjamin Petersonc4311282012-10-30 23:21:10 -040015145 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15146 Py_FatalError("Can't initialize field name iterator type");
15147
15148 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15149 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015150
Victor Stinner3a50e702011-10-18 21:21:00 +020015151 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015152}
15153
15154/* Finalize the Unicode implementation */
15155
Christian Heimesa156e092008-02-16 07:38:31 +000015156int
15157PyUnicode_ClearFreeList(void)
15158{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015159 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015160}
15161
Guido van Rossumd57fd912000-03-10 22:53:23 +000015162void
Thomas Wouters78890102000-07-22 19:25:51 +000015163_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015164{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015165 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015166
Serhiy Storchaka05997252013-01-26 12:14:02 +020015167 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015168
Serhiy Storchaka05997252013-01-26 12:14:02 +020015169 for (i = 0; i < 256; i++)
15170 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015171 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015172 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015173}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015174
Walter Dörwald16807132007-05-25 13:52:07 +000015175void
15176PyUnicode_InternInPlace(PyObject **p)
15177{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015178 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015179 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015180#ifdef Py_DEBUG
15181 assert(s != NULL);
15182 assert(_PyUnicode_CHECK(s));
15183#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015184 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015185 return;
15186#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015187 /* If it's a subclass, we don't really know what putting
15188 it in the interned dict might do. */
15189 if (!PyUnicode_CheckExact(s))
15190 return;
15191 if (PyUnicode_CHECK_INTERNED(s))
15192 return;
15193 if (interned == NULL) {
15194 interned = PyDict_New();
15195 if (interned == NULL) {
15196 PyErr_Clear(); /* Don't leave an exception */
15197 return;
15198 }
15199 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015200 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015201 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015203 if (t == NULL) {
15204 PyErr_Clear();
15205 return;
15206 }
15207 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015208 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015209 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015210 return;
15211 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015212 /* The two references in interned are not counted by refcnt.
15213 The deallocator will take care of this */
15214 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015215 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015216}
15217
15218void
15219PyUnicode_InternImmortal(PyObject **p)
15220{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015221 PyUnicode_InternInPlace(p);
15222 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015223 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015224 Py_INCREF(*p);
15225 }
Walter Dörwald16807132007-05-25 13:52:07 +000015226}
15227
15228PyObject *
15229PyUnicode_InternFromString(const char *cp)
15230{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015231 PyObject *s = PyUnicode_FromString(cp);
15232 if (s == NULL)
15233 return NULL;
15234 PyUnicode_InternInPlace(&s);
15235 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015236}
15237
Alexander Belopolsky40018472011-02-26 01:02:56 +000015238void
15239_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015240{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015241 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015242 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015243 Py_ssize_t i, n;
15244 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015245
Benjamin Peterson14339b62009-01-31 16:36:08 +000015246 if (interned == NULL || !PyDict_Check(interned))
15247 return;
15248 keys = PyDict_Keys(interned);
15249 if (keys == NULL || !PyList_Check(keys)) {
15250 PyErr_Clear();
15251 return;
15252 }
Walter Dörwald16807132007-05-25 13:52:07 +000015253
Benjamin Peterson14339b62009-01-31 16:36:08 +000015254 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15255 detector, interned unicode strings are not forcibly deallocated;
15256 rather, we give them their stolen references back, and then clear
15257 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015258
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 n = PyList_GET_SIZE(keys);
15260 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015261 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015262 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015263 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015264 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015265 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015267 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 case SSTATE_NOT_INTERNED:
15269 /* XXX Shouldn't happen */
15270 break;
15271 case SSTATE_INTERNED_IMMORTAL:
15272 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015273 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015274 break;
15275 case SSTATE_INTERNED_MORTAL:
15276 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015277 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015278 break;
15279 default:
15280 Py_FatalError("Inconsistent interned string state.");
15281 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015282 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015283 }
15284 fprintf(stderr, "total size of all interned strings: "
15285 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15286 "mortal/immortal\n", mortal_size, immortal_size);
15287 Py_DECREF(keys);
15288 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015289 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015290}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015291
15292
15293/********************* Unicode Iterator **************************/
15294
15295typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015296 PyObject_HEAD
15297 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015298 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015299} unicodeiterobject;
15300
15301static void
15302unicodeiter_dealloc(unicodeiterobject *it)
15303{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015304 _PyObject_GC_UNTRACK(it);
15305 Py_XDECREF(it->it_seq);
15306 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015307}
15308
15309static int
15310unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15311{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015312 Py_VISIT(it->it_seq);
15313 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015314}
15315
15316static PyObject *
15317unicodeiter_next(unicodeiterobject *it)
15318{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015319 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015320
Benjamin Peterson14339b62009-01-31 16:36:08 +000015321 assert(it != NULL);
15322 seq = it->it_seq;
15323 if (seq == NULL)
15324 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015325 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015327 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15328 int kind = PyUnicode_KIND(seq);
15329 void *data = PyUnicode_DATA(seq);
15330 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15331 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015332 if (item != NULL)
15333 ++it->it_index;
15334 return item;
15335 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015336
Benjamin Peterson14339b62009-01-31 16:36:08 +000015337 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015338 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015339 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015340}
15341
15342static PyObject *
15343unicodeiter_len(unicodeiterobject *it)
15344{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015345 Py_ssize_t len = 0;
15346 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015347 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015348 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015349}
15350
15351PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15352
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015353static PyObject *
15354unicodeiter_reduce(unicodeiterobject *it)
15355{
15356 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015357 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015358 it->it_seq, it->it_index);
15359 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015360 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015361 if (u == NULL)
15362 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015363 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015364 }
15365}
15366
15367PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15368
15369static PyObject *
15370unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15371{
15372 Py_ssize_t index = PyLong_AsSsize_t(state);
15373 if (index == -1 && PyErr_Occurred())
15374 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015375 if (it->it_seq != NULL) {
15376 if (index < 0)
15377 index = 0;
15378 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15379 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15380 it->it_index = index;
15381 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015382 Py_RETURN_NONE;
15383}
15384
15385PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15386
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015387static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015388 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015389 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015390 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15391 reduce_doc},
15392 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15393 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015394 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015395};
15396
15397PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015398 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15399 "str_iterator", /* tp_name */
15400 sizeof(unicodeiterobject), /* tp_basicsize */
15401 0, /* tp_itemsize */
15402 /* methods */
15403 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15404 0, /* tp_print */
15405 0, /* tp_getattr */
15406 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015407 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015408 0, /* tp_repr */
15409 0, /* tp_as_number */
15410 0, /* tp_as_sequence */
15411 0, /* tp_as_mapping */
15412 0, /* tp_hash */
15413 0, /* tp_call */
15414 0, /* tp_str */
15415 PyObject_GenericGetAttr, /* tp_getattro */
15416 0, /* tp_setattro */
15417 0, /* tp_as_buffer */
15418 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15419 0, /* tp_doc */
15420 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15421 0, /* tp_clear */
15422 0, /* tp_richcompare */
15423 0, /* tp_weaklistoffset */
15424 PyObject_SelfIter, /* tp_iter */
15425 (iternextfunc)unicodeiter_next, /* tp_iternext */
15426 unicodeiter_methods, /* tp_methods */
15427 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015428};
15429
15430static PyObject *
15431unicode_iter(PyObject *seq)
15432{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015433 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015434
Benjamin Peterson14339b62009-01-31 16:36:08 +000015435 if (!PyUnicode_Check(seq)) {
15436 PyErr_BadInternalCall();
15437 return NULL;
15438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015439 if (PyUnicode_READY(seq) == -1)
15440 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015441 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15442 if (it == NULL)
15443 return NULL;
15444 it->it_index = 0;
15445 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015446 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015447 _PyObject_GC_TRACK(it);
15448 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015449}
15450
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015451
15452size_t
15453Py_UNICODE_strlen(const Py_UNICODE *u)
15454{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015455 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015456}
15457
15458Py_UNICODE*
15459Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15460{
15461 Py_UNICODE *u = s1;
15462 while ((*u++ = *s2++));
15463 return s1;
15464}
15465
15466Py_UNICODE*
15467Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15468{
15469 Py_UNICODE *u = s1;
15470 while ((*u++ = *s2++))
15471 if (n-- == 0)
15472 break;
15473 return s1;
15474}
15475
15476Py_UNICODE*
15477Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15478{
15479 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015480 u1 += wcslen(u1);
15481 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015482 return s1;
15483}
15484
15485int
15486Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15487{
15488 while (*s1 && *s2 && *s1 == *s2)
15489 s1++, s2++;
15490 if (*s1 && *s2)
15491 return (*s1 < *s2) ? -1 : +1;
15492 if (*s1)
15493 return 1;
15494 if (*s2)
15495 return -1;
15496 return 0;
15497}
15498
15499int
15500Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15501{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015502 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015503 for (; n != 0; n--) {
15504 u1 = *s1;
15505 u2 = *s2;
15506 if (u1 != u2)
15507 return (u1 < u2) ? -1 : +1;
15508 if (u1 == '\0')
15509 return 0;
15510 s1++;
15511 s2++;
15512 }
15513 return 0;
15514}
15515
15516Py_UNICODE*
15517Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15518{
15519 const Py_UNICODE *p;
15520 for (p = s; *p; p++)
15521 if (*p == c)
15522 return (Py_UNICODE*)p;
15523 return NULL;
15524}
15525
15526Py_UNICODE*
15527Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15528{
15529 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015530 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015531 while (p != s) {
15532 p--;
15533 if (*p == c)
15534 return (Py_UNICODE*)p;
15535 }
15536 return NULL;
15537}
Victor Stinner331ea922010-08-10 16:37:20 +000015538
Victor Stinner71133ff2010-09-01 23:43:53 +000015539Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015540PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015541{
Victor Stinner577db2c2011-10-11 22:12:48 +020015542 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015543 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015544
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015545 if (!PyUnicode_Check(unicode)) {
15546 PyErr_BadArgument();
15547 return NULL;
15548 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015549 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015550 if (u == NULL)
15551 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015552 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015553 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015554 PyErr_NoMemory();
15555 return NULL;
15556 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015557 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015558 size *= sizeof(Py_UNICODE);
15559 copy = PyMem_Malloc(size);
15560 if (copy == NULL) {
15561 PyErr_NoMemory();
15562 return NULL;
15563 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015564 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015565 return copy;
15566}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015567
Georg Brandl66c221e2010-10-14 07:04:07 +000015568/* A _string module, to export formatter_parser and formatter_field_name_split
15569 to the string.Formatter class implemented in Python. */
15570
15571static PyMethodDef _string_methods[] = {
15572 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15573 METH_O, PyDoc_STR("split the argument as a field name")},
15574 {"formatter_parser", (PyCFunction) formatter_parser,
15575 METH_O, PyDoc_STR("parse the argument as a format string")},
15576 {NULL, NULL}
15577};
15578
15579static struct PyModuleDef _string_module = {
15580 PyModuleDef_HEAD_INIT,
15581 "_string",
15582 PyDoc_STR("string helper module"),
15583 0,
15584 _string_methods,
15585 NULL,
15586 NULL,
15587 NULL,
15588 NULL
15589};
15590
15591PyMODINIT_FUNC
15592PyInit__string(void)
15593{
15594 return PyModule_Create(&_string_module);
15595}
15596
15597
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015598#ifdef __cplusplus
15599}
15600#endif