blob: 07330119dc30380950c3b8896bfff4c474d5d74d [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;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004193 PyObject *inputobj = NULL;
4194
4195 if (*errorHandler == NULL) {
4196 *errorHandler = PyCodec_LookupError(errors);
4197 if (*errorHandler == NULL)
4198 goto onError;
4199 }
4200
4201 make_decode_exception(exceptionObject,
4202 encoding,
4203 *input, *inend - *input,
4204 *startinpos, *endinpos,
4205 reason);
4206 if (*exceptionObject == NULL)
4207 goto onError;
4208
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004209 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004210 if (restuple == NULL)
4211 goto onError;
4212 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004213 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004214 goto onError;
4215 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004216 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004217 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004218
4219 /* Copy back the bytes variables, which might have been modified by the
4220 callback */
4221 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4222 if (!inputobj)
4223 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004224 *input = PyBytes_AS_STRING(inputobj);
4225 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004226 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004227 /* we can DECREF safely, as the exception has another reference,
4228 so the object won't go away. */
4229 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004230
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004231 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004232 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004233 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004234 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004235 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004236 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004237
Victor Stinner170ca6f2013-04-18 00:25:28 +02004238 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004239 if (replen > 1) {
4240 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004241 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004242 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4243 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4244 goto onError;
4245 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004246 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004247 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004248
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004249 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004250 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004251
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004252 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004253 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004254 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004255
Benjamin Peterson29060642009-01-31 22:14:21 +00004256 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004257 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004258 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004259}
4260
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004261/* --- UTF-7 Codec -------------------------------------------------------- */
4262
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263/* See RFC2152 for details. We encode conservatively and decode liberally. */
4264
4265/* Three simple macros defining base-64. */
4266
4267/* Is c a base-64 character? */
4268
4269#define IS_BASE64(c) \
4270 (((c) >= 'A' && (c) <= 'Z') || \
4271 ((c) >= 'a' && (c) <= 'z') || \
4272 ((c) >= '0' && (c) <= '9') || \
4273 (c) == '+' || (c) == '/')
4274
4275/* given that c is a base-64 character, what is its base-64 value? */
4276
4277#define FROM_BASE64(c) \
4278 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4279 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4280 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4281 (c) == '+' ? 62 : 63)
4282
4283/* What is the base-64 character of the bottom 6 bits of n? */
4284
4285#define TO_BASE64(n) \
4286 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4287
4288/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4289 * decoded as itself. We are permissive on decoding; the only ASCII
4290 * byte not decoding to itself is the + which begins a base64
4291 * string. */
4292
4293#define DECODE_DIRECT(c) \
4294 ((c) <= 127 && (c) != '+')
4295
4296/* The UTF-7 encoder treats ASCII characters differently according to
4297 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4298 * the above). See RFC2152. This array identifies these different
4299 * sets:
4300 * 0 : "Set D"
4301 * alphanumeric and '(),-./:?
4302 * 1 : "Set O"
4303 * !"#$%&*;<=>@[]^_`{|}
4304 * 2 : "whitespace"
4305 * ht nl cr sp
4306 * 3 : special (must be base64 encoded)
4307 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4308 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004309
Tim Petersced69f82003-09-16 20:30:58 +00004310static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004311char utf7_category[128] = {
4312/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4313 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4314/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4315 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4316/* sp ! " # $ % & ' ( ) * + , - . / */
4317 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4318/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4319 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4320/* @ A B C D E F G H I J K L M N O */
4321 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4322/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4323 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4324/* ` a b c d e f g h i j k l m n o */
4325 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4326/* p q r s t u v w x y z { | } ~ del */
4327 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004328};
4329
Antoine Pitrou244651a2009-05-04 18:56:13 +00004330/* ENCODE_DIRECT: this character should be encoded as itself. The
4331 * answer depends on whether we are encoding set O as itself, and also
4332 * on whether we are encoding whitespace as itself. RFC2152 makes it
4333 * clear that the answers to these questions vary between
4334 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004335
Antoine Pitrou244651a2009-05-04 18:56:13 +00004336#define ENCODE_DIRECT(c, directO, directWS) \
4337 ((c) < 128 && (c) > 0 && \
4338 ((utf7_category[(c)] == 0) || \
4339 (directWS && (utf7_category[(c)] == 2)) || \
4340 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341
Alexander Belopolsky40018472011-02-26 01:02:56 +00004342PyObject *
4343PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004344 Py_ssize_t size,
4345 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004346{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004347 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4348}
4349
Antoine Pitrou244651a2009-05-04 18:56:13 +00004350/* The decoder. The only state we preserve is our read position,
4351 * i.e. how many characters we have consumed. So if we end in the
4352 * middle of a shift sequence we have to back off the read position
4353 * and the output to the beginning of the sequence, otherwise we lose
4354 * all the shift state (seen bits, number of bits seen, high
4355 * surrogate). */
4356
Alexander Belopolsky40018472011-02-26 01:02:56 +00004357PyObject *
4358PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004359 Py_ssize_t size,
4360 const char *errors,
4361 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004362{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004363 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004364 Py_ssize_t startinpos;
4365 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004366 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004367 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004368 const char *errmsg = "";
4369 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004370 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 unsigned int base64bits = 0;
4372 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004373 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004374 PyObject *errorHandler = NULL;
4375 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004376
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004377 if (size == 0) {
4378 if (consumed)
4379 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004380 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004381 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004382
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004383 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004384 _PyUnicodeWriter_Init(&writer);
4385 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004386
4387 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004388 e = s + size;
4389
4390 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004391 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004392 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004393 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004394
Antoine Pitrou244651a2009-05-04 18:56:13 +00004395 if (inShift) { /* in a base-64 section */
4396 if (IS_BASE64(ch)) { /* consume a base-64 character */
4397 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4398 base64bits += 6;
4399 s++;
4400 if (base64bits >= 16) {
4401 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004402 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 base64bits -= 16;
4404 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004405 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004406 if (surrogate) {
4407 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004408 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4409 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004410 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004411 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004413 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414 }
4415 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004416 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004417 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 }
4420 }
Victor Stinner551ac952011-11-29 22:58:13 +01004421 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004422 /* first surrogate */
4423 surrogate = outCh;
4424 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004426 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004427 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004428 }
4429 }
4430 }
4431 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004433 if (base64bits > 0) { /* left-over bits */
4434 if (base64bits >= 6) {
4435 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004436 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004437 errmsg = "partial character in shift sequence";
4438 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004439 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 else {
4441 /* Some bits remain; they should be zero */
4442 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004443 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004444 errmsg = "non-zero padding bits in shift sequence";
4445 goto utf7Error;
4446 }
4447 }
4448 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004449 if (surrogate && DECODE_DIRECT(ch)) {
4450 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4451 goto onError;
4452 }
4453 surrogate = 0;
4454 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004455 /* '-' is absorbed; other terminating
4456 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004457 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004458 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004459 }
4460 }
4461 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004462 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004463 s++; /* consume '+' */
4464 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004465 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004466 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004467 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 }
4469 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004470 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004471 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004472 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004474 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004475 }
4476 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004477 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004478 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004479 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004480 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004482 else {
4483 startinpos = s-starts;
4484 s++;
4485 errmsg = "unexpected special character";
4486 goto utf7Error;
4487 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004490 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004491 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004492 errors, &errorHandler,
4493 "utf7", errmsg,
4494 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004495 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004496 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497 }
4498
Antoine Pitrou244651a2009-05-04 18:56:13 +00004499 /* end of string */
4500
4501 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4502 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004503 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504 if (surrogate ||
4505 (base64bits >= 6) ||
4506 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004508 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004509 errors, &errorHandler,
4510 "utf7", "unterminated shift sequence",
4511 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004512 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004513 goto onError;
4514 if (s < e)
4515 goto restart;
4516 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004518
4519 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004520 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004521 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004522 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004523 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004524 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004525 writer.kind, writer.data, shiftOutStart);
4526 Py_XDECREF(errorHandler);
4527 Py_XDECREF(exc);
4528 _PyUnicodeWriter_Dealloc(&writer);
4529 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004530 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004531 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004532 }
4533 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004534 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004536 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004537
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004538 Py_XDECREF(errorHandler);
4539 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004540 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004541
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004543 Py_XDECREF(errorHandler);
4544 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004545 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004546 return NULL;
4547}
4548
4549
Alexander Belopolsky40018472011-02-26 01:02:56 +00004550PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004551_PyUnicode_EncodeUTF7(PyObject *str,
4552 int base64SetO,
4553 int base64WhiteSpace,
4554 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004555{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004556 int kind;
4557 void *data;
4558 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004559 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004560 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004561 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004562 unsigned int base64bits = 0;
4563 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004564 char * out;
4565 char * start;
4566
Benjamin Petersonbac79492012-01-14 13:34:47 -05004567 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004568 return NULL;
4569 kind = PyUnicode_KIND(str);
4570 data = PyUnicode_DATA(str);
4571 len = PyUnicode_GET_LENGTH(str);
4572
4573 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004574 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004575
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004576 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004577 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004578 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004579 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004580 if (v == NULL)
4581 return NULL;
4582
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004583 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004584 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004585 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004586
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 if (inShift) {
4588 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4589 /* shifting out */
4590 if (base64bits) { /* output remaining bits */
4591 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4592 base64buffer = 0;
4593 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004594 }
4595 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 /* Characters not in the BASE64 set implicitly unshift the sequence
4597 so no '-' is required, except if the character is itself a '-' */
4598 if (IS_BASE64(ch) || ch == '-') {
4599 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004600 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004601 *out++ = (char) ch;
4602 }
4603 else {
4604 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004605 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004606 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004607 else { /* not in a shift sequence */
4608 if (ch == '+') {
4609 *out++ = '+';
4610 *out++ = '-';
4611 }
4612 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4613 *out++ = (char) ch;
4614 }
4615 else {
4616 *out++ = '+';
4617 inShift = 1;
4618 goto encode_char;
4619 }
4620 }
4621 continue;
4622encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004623 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004624 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004625
Antoine Pitrou244651a2009-05-04 18:56:13 +00004626 /* code first surrogate */
4627 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004628 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004629 while (base64bits >= 6) {
4630 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4631 base64bits -= 6;
4632 }
4633 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004634 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004635 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004636 base64bits += 16;
4637 base64buffer = (base64buffer << 16) | ch;
4638 while (base64bits >= 6) {
4639 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4640 base64bits -= 6;
4641 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004642 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004643 if (base64bits)
4644 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4645 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004646 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004647 if (_PyBytes_Resize(&v, out - start) < 0)
4648 return NULL;
4649 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004650}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004651PyObject *
4652PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4653 Py_ssize_t size,
4654 int base64SetO,
4655 int base64WhiteSpace,
4656 const char *errors)
4657{
4658 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004659 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004660 if (tmp == NULL)
4661 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004662 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004663 base64WhiteSpace, errors);
4664 Py_DECREF(tmp);
4665 return result;
4666}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004667
Antoine Pitrou244651a2009-05-04 18:56:13 +00004668#undef IS_BASE64
4669#undef FROM_BASE64
4670#undef TO_BASE64
4671#undef DECODE_DIRECT
4672#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004673
Guido van Rossumd57fd912000-03-10 22:53:23 +00004674/* --- UTF-8 Codec -------------------------------------------------------- */
4675
Alexander Belopolsky40018472011-02-26 01:02:56 +00004676PyObject *
4677PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004678 Py_ssize_t size,
4679 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004680{
Walter Dörwald69652032004-09-07 20:24:22 +00004681 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4682}
4683
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004684#include "stringlib/asciilib.h"
4685#include "stringlib/codecs.h"
4686#include "stringlib/undef.h"
4687
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004688#include "stringlib/ucs1lib.h"
4689#include "stringlib/codecs.h"
4690#include "stringlib/undef.h"
4691
4692#include "stringlib/ucs2lib.h"
4693#include "stringlib/codecs.h"
4694#include "stringlib/undef.h"
4695
4696#include "stringlib/ucs4lib.h"
4697#include "stringlib/codecs.h"
4698#include "stringlib/undef.h"
4699
Antoine Pitrouab868312009-01-10 15:40:25 +00004700/* Mask to quickly check whether a C 'long' contains a
4701 non-ASCII, UTF8-encoded char. */
4702#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004703# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004704#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004705# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004706#else
4707# error C 'long' size should be either 4 or 8!
4708#endif
4709
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004710static Py_ssize_t
4711ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004712{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004713 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004714 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004715
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004716 /*
4717 * Issue #17237: m68k is a bit different from most architectures in
4718 * that objects do not use "natural alignment" - for example, int and
4719 * long are only aligned at 2-byte boundaries. Therefore the assert()
4720 * won't work; also, tests have shown that skipping the "optimised
4721 * version" will even speed up m68k.
4722 */
4723#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004725 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4726 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 /* Fast path, see in STRINGLIB(utf8_decode) for
4728 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004729 /* Help allocation */
4730 const char *_p = p;
4731 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004732 while (_p < aligned_end) {
4733 unsigned long value = *(const unsigned long *) _p;
4734 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004735 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004736 *((unsigned long *)q) = value;
4737 _p += SIZEOF_LONG;
4738 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004739 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004740 p = _p;
4741 while (p < end) {
4742 if ((unsigned char)*p & 0x80)
4743 break;
4744 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004745 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004746 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004747 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004748#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004749#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 while (p < end) {
4751 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4752 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004753 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004754 /* Help allocation */
4755 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004756 while (_p < aligned_end) {
4757 unsigned long value = *(unsigned long *) _p;
4758 if (value & ASCII_CHAR_MASK)
4759 break;
4760 _p += SIZEOF_LONG;
4761 }
4762 p = _p;
4763 if (_p == end)
4764 break;
4765 }
4766 if ((unsigned char)*p & 0x80)
4767 break;
4768 ++p;
4769 }
4770 memcpy(dest, start, p - start);
4771 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004772}
Antoine Pitrouab868312009-01-10 15:40:25 +00004773
Victor Stinner785938e2011-12-11 20:09:03 +01004774PyObject *
4775PyUnicode_DecodeUTF8Stateful(const char *s,
4776 Py_ssize_t size,
4777 const char *errors,
4778 Py_ssize_t *consumed)
4779{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004780 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004781 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004782 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004783
4784 Py_ssize_t startinpos;
4785 Py_ssize_t endinpos;
4786 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004787 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004788 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004789 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004790
4791 if (size == 0) {
4792 if (consumed)
4793 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004794 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004795 }
4796
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004797 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4798 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004799 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 *consumed = 1;
4801 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004802 }
4803
Victor Stinner8f674cc2013-04-17 23:02:17 +02004804 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004805 writer.min_length = size;
4806 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004807 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004808
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004809 writer.pos = ascii_decode(s, end, writer.data);
4810 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 while (s < end) {
4812 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004813 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004814
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004815 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004816 if (PyUnicode_IS_ASCII(writer.buffer))
4817 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004818 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004819 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004820 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004821 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004822 } else {
4823 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004824 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004825 }
4826
4827 switch (ch) {
4828 case 0:
4829 if (s == end || consumed)
4830 goto End;
4831 errmsg = "unexpected end of data";
4832 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004833 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004834 break;
4835 case 1:
4836 errmsg = "invalid start byte";
4837 startinpos = s - starts;
4838 endinpos = startinpos + 1;
4839 break;
4840 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004841 case 3:
4842 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 errmsg = "invalid continuation byte";
4844 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004845 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004846 break;
4847 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004848 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 goto onError;
4850 continue;
4851 }
4852
Victor Stinner1d65d912015-10-05 13:43:50 +02004853 if (error_handler == _Py_ERROR_UNKNOWN)
4854 error_handler = get_error_handler(errors);
4855
4856 switch (error_handler) {
4857 case _Py_ERROR_IGNORE:
4858 s += (endinpos - startinpos);
4859 break;
4860
4861 case _Py_ERROR_REPLACE:
4862 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4863 goto onError;
4864 s += (endinpos - startinpos);
4865 break;
4866
4867 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004868 {
4869 Py_ssize_t i;
4870
Victor Stinner1d65d912015-10-05 13:43:50 +02004871 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4872 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004873 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004874 ch = (Py_UCS4)(unsigned char)(starts[i]);
4875 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4876 ch + 0xdc00);
4877 writer.pos++;
4878 }
4879 s += (endinpos - startinpos);
4880 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004881 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004882
4883 default:
4884 if (unicode_decode_call_errorhandler_writer(
4885 errors, &error_handler_obj,
4886 "utf-8", errmsg,
4887 &starts, &end, &startinpos, &endinpos, &exc, &s,
4888 &writer))
4889 goto onError;
4890 }
Victor Stinner785938e2011-12-11 20:09:03 +01004891 }
4892
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004893End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004894 if (consumed)
4895 *consumed = s - starts;
4896
Victor Stinner1d65d912015-10-05 13:43:50 +02004897 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004898 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004899 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004900
4901onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004902 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004903 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004904 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004905 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004906}
4907
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004908
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004909/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4910 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004911
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004912 On success, write a pointer to a newly allocated wide character string into
4913 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4914 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004915
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004916 On memory allocation failure, return -1.
4917
4918 On decoding error (if surrogateescape is zero), return -2. If wlen is
4919 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4920 is not NULL, write the decoding error message into *reason. */
4921int
4922_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
4923 const char **reason, int surrogateescape)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004924{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004925 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004926 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004927 wchar_t *unicode;
4928 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004929
4930 /* Note: size will always be longer than the resulting Unicode
4931 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004932 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004933 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004934 }
4935
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004936 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004937 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004938 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004939 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004940
4941 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004942 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004943 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004944 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004945 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004946#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004947 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004948#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004949 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004950#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004951 if (ch > 0xFF) {
4952#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07004953 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004954#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02004955 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004956 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004957 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4958 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4959#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004960 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004961 else {
4962 if (!ch && s == e)
4963 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004964 if (!surrogateescape) {
4965 PyMem_RawFree(unicode );
4966 if (reason != NULL) {
4967 switch (ch) {
4968 case 0:
4969 *reason = "unexpected end of data";
4970 break;
4971 case 1:
4972 *reason = "invalid start byte";
4973 break;
4974 /* 2, 3, 4 */
4975 default:
4976 *reason = "invalid continuation byte";
4977 break;
4978 }
4979 }
4980 if (wlen != NULL) {
4981 *wlen = s - orig_s;
4982 }
4983 return -2;
4984 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004985 /* surrogateescape */
4986 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4987 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004988 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004989 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004990 if (wlen) {
4991 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01004992 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004993 *wstr = unicode;
4994 return 0;
4995}
4996
4997wchar_t*
4998_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen)
4999{
5000 wchar_t *wstr;
5001 int res = _Py_DecodeUTF8Ex(arg, arglen, &wstr, NULL, NULL, 1);
5002 if (res != 0) {
5003 return NULL;
5004 }
5005 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005006}
5007
Antoine Pitrouab868312009-01-10 15:40:25 +00005008
Victor Stinnere47e6982017-12-21 15:45:16 +01005009/* UTF-8 encoder using the surrogateescape error handler .
5010
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005011 On success, return 0 and write the newly allocated character string (use
5012 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005013
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005014 On encoding failure, return -2 and write the position of the invalid
5015 surrogate character into *error_pos (if error_pos is set) and the decoding
5016 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005017
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005018 On memory allocation failure, return -1. */
5019int
5020_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
5021 const char **reason, int raw_malloc, int surrogateescape)
Victor Stinnere47e6982017-12-21 15:45:16 +01005022{
5023 const Py_ssize_t max_char_size = 4;
5024 Py_ssize_t len = wcslen(text);
5025
5026 assert(len >= 0);
5027
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005028 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5029 return -1;
5030 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005031 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005032 if (raw_malloc) {
5033 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005034 }
5035 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005036 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005037 }
5038 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005039 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005040 }
5041
5042 char *p = bytes;
5043 Py_ssize_t i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005044 for (i = 0; i < len; i++) {
5045 Py_UCS4 ch = text[i];
Victor Stinnere47e6982017-12-21 15:45:16 +01005046
5047 if (ch < 0x80) {
5048 /* Encode ASCII */
5049 *p++ = (char) ch;
5050
5051 }
5052 else if (ch < 0x0800) {
5053 /* Encode Latin-1 */
5054 *p++ = (char)(0xc0 | (ch >> 6));
5055 *p++ = (char)(0x80 | (ch & 0x3f));
5056 }
5057 else if (Py_UNICODE_IS_SURROGATE(ch)) {
5058 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005059 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005060 if (error_pos != NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005061 *error_pos = (size_t)i;
Victor Stinnere47e6982017-12-21 15:45:16 +01005062 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005063 if (reason != NULL) {
5064 *reason = "encoding error";
5065 }
5066 if (raw_malloc) {
5067 PyMem_RawFree(bytes);
5068 }
5069 else {
5070 PyMem_Free(bytes);
5071 }
5072 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005073 }
5074 *p++ = (char)(ch & 0xff);
5075 }
5076 else if (ch < 0x10000) {
5077 *p++ = (char)(0xe0 | (ch >> 12));
5078 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5079 *p++ = (char)(0x80 | (ch & 0x3f));
5080 }
5081 else { /* ch >= 0x10000 */
5082 assert(ch <= MAX_UNICODE);
5083 /* Encode UCS4 Unicode ordinals */
5084 *p++ = (char)(0xf0 | (ch >> 18));
5085 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5086 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5087 *p++ = (char)(0x80 | (ch & 0x3f));
5088 }
5089 }
5090 *p++ = '\0';
5091
5092 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005093 char *bytes2;
5094 if (raw_malloc) {
5095 bytes2 = PyMem_RawRealloc(bytes, final_size);
5096 }
5097 else {
5098 bytes2 = PyMem_Realloc(bytes, final_size);
5099 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005100 if (bytes2 == NULL) {
5101 if (error_pos != NULL) {
5102 *error_pos = (size_t)-1;
5103 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005104 if (raw_malloc) {
5105 PyMem_RawFree(bytes);
5106 }
5107 else {
5108 PyMem_Free(bytes);
5109 }
5110 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005111 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005112 *str = bytes2;
5113 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005114}
5115
5116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005117/* Primary internal function which creates utf8 encoded bytes objects.
5118
5119 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005120 and allocate exactly as much space needed at the end. Else allocate the
5121 maximum possible needed (4 result bytes per Unicode character), and return
5122 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005123*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005124PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005125_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005126{
Victor Stinner6099a032011-12-18 14:22:26 +01005127 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005128 void *data;
5129 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005131 if (!PyUnicode_Check(unicode)) {
5132 PyErr_BadArgument();
5133 return NULL;
5134 }
5135
5136 if (PyUnicode_READY(unicode) == -1)
5137 return NULL;
5138
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005139 if (PyUnicode_UTF8(unicode))
5140 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5141 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005142
5143 kind = PyUnicode_KIND(unicode);
5144 data = PyUnicode_DATA(unicode);
5145 size = PyUnicode_GET_LENGTH(unicode);
5146
Benjamin Petersonead6b532011-12-20 17:23:42 -06005147 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005148 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005149 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005150 case PyUnicode_1BYTE_KIND:
5151 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5152 assert(!PyUnicode_IS_ASCII(unicode));
5153 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5154 case PyUnicode_2BYTE_KIND:
5155 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5156 case PyUnicode_4BYTE_KIND:
5157 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005158 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005159}
5160
Alexander Belopolsky40018472011-02-26 01:02:56 +00005161PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005162PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5163 Py_ssize_t size,
5164 const char *errors)
5165{
5166 PyObject *v, *unicode;
5167
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005168 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005169 if (unicode == NULL)
5170 return NULL;
5171 v = _PyUnicode_AsUTF8String(unicode, errors);
5172 Py_DECREF(unicode);
5173 return v;
5174}
5175
5176PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005177PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005178{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005179 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005180}
5181
Walter Dörwald41980ca2007-08-16 21:55:45 +00005182/* --- UTF-32 Codec ------------------------------------------------------- */
5183
5184PyObject *
5185PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005186 Py_ssize_t size,
5187 const char *errors,
5188 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005189{
5190 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5191}
5192
5193PyObject *
5194PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005195 Py_ssize_t size,
5196 const char *errors,
5197 int *byteorder,
5198 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005199{
5200 const char *starts = s;
5201 Py_ssize_t startinpos;
5202 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005203 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005204 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005205 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005206 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005207 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005208 PyObject *errorHandler = NULL;
5209 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005210
Walter Dörwald41980ca2007-08-16 21:55:45 +00005211 q = (unsigned char *)s;
5212 e = q + size;
5213
5214 if (byteorder)
5215 bo = *byteorder;
5216
5217 /* Check for BOM marks (U+FEFF) in the input and adjust current
5218 byte order setting accordingly. In native mode, the leading BOM
5219 mark is skipped, in all other modes, it is copied to the output
5220 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005221 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005222 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005223 if (bom == 0x0000FEFF) {
5224 bo = -1;
5225 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005226 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005227 else if (bom == 0xFFFE0000) {
5228 bo = 1;
5229 q += 4;
5230 }
5231 if (byteorder)
5232 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005233 }
5234
Victor Stinnere64322e2012-10-30 23:12:47 +01005235 if (q == e) {
5236 if (consumed)
5237 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005238 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005239 }
5240
Victor Stinnere64322e2012-10-30 23:12:47 +01005241#ifdef WORDS_BIGENDIAN
5242 le = bo < 0;
5243#else
5244 le = bo <= 0;
5245#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005246 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005247
Victor Stinner8f674cc2013-04-17 23:02:17 +02005248 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005249 writer.min_length = (e - q + 3) / 4;
5250 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005251 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005252
Victor Stinnere64322e2012-10-30 23:12:47 +01005253 while (1) {
5254 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005255 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005256
Victor Stinnere64322e2012-10-30 23:12:47 +01005257 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005258 enum PyUnicode_Kind kind = writer.kind;
5259 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005260 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005261 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005262 if (le) {
5263 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005264 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005265 if (ch > maxch)
5266 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005267 if (kind != PyUnicode_1BYTE_KIND &&
5268 Py_UNICODE_IS_SURROGATE(ch))
5269 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005270 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005271 q += 4;
5272 } while (q <= last);
5273 }
5274 else {
5275 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005276 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005277 if (ch > maxch)
5278 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005279 if (kind != PyUnicode_1BYTE_KIND &&
5280 Py_UNICODE_IS_SURROGATE(ch))
5281 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005282 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005283 q += 4;
5284 } while (q <= last);
5285 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005286 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005287 }
5288
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005289 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005290 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005291 startinpos = ((const char *)q) - starts;
5292 endinpos = startinpos + 4;
5293 }
5294 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005295 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005296 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005297 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005298 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005299 startinpos = ((const char *)q) - starts;
5300 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005301 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005302 else {
5303 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005304 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005305 goto onError;
5306 q += 4;
5307 continue;
5308 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005309 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005310 startinpos = ((const char *)q) - starts;
5311 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005313
5314 /* The remaining input chars are ignored if the callback
5315 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005316 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005318 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005320 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322 }
5323
Walter Dörwald41980ca2007-08-16 21:55:45 +00005324 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005326
Walter Dörwald41980ca2007-08-16 21:55:45 +00005327 Py_XDECREF(errorHandler);
5328 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005329 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005330
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005332 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005333 Py_XDECREF(errorHandler);
5334 Py_XDECREF(exc);
5335 return NULL;
5336}
5337
5338PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005339_PyUnicode_EncodeUTF32(PyObject *str,
5340 const char *errors,
5341 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005342{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005343 enum PyUnicode_Kind kind;
5344 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005345 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005346 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005347 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005348#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005349 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005350#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005351 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005352#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005353 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005354 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005355 PyObject *errorHandler = NULL;
5356 PyObject *exc = NULL;
5357 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005358
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005359 if (!PyUnicode_Check(str)) {
5360 PyErr_BadArgument();
5361 return NULL;
5362 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005363 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005364 return NULL;
5365 kind = PyUnicode_KIND(str);
5366 data = PyUnicode_DATA(str);
5367 len = PyUnicode_GET_LENGTH(str);
5368
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005369 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005370 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005371 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005372 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005373 if (v == NULL)
5374 return NULL;
5375
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005376 /* output buffer is 4-bytes aligned */
5377 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005378 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005379 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005380 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005381 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005382 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005383
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005384 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005385 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005386 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005387 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005388 else
5389 encoding = "utf-32";
5390
5391 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005392 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5393 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005394 }
5395
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005396 pos = 0;
5397 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005398 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005399
5400 if (kind == PyUnicode_2BYTE_KIND) {
5401 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5402 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005403 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005404 else {
5405 assert(kind == PyUnicode_4BYTE_KIND);
5406 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5407 &out, native_ordering);
5408 }
5409 if (pos == len)
5410 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005411
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005412 rep = unicode_encode_call_errorhandler(
5413 errors, &errorHandler,
5414 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005415 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005416 if (!rep)
5417 goto error;
5418
5419 if (PyBytes_Check(rep)) {
5420 repsize = PyBytes_GET_SIZE(rep);
5421 if (repsize & 3) {
5422 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005423 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005424 "surrogates not allowed");
5425 goto error;
5426 }
5427 moreunits = repsize / 4;
5428 }
5429 else {
5430 assert(PyUnicode_Check(rep));
5431 if (PyUnicode_READY(rep) < 0)
5432 goto error;
5433 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5434 if (!PyUnicode_IS_ASCII(rep)) {
5435 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005436 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005437 "surrogates not allowed");
5438 goto error;
5439 }
5440 }
5441
5442 /* four bytes are reserved for each surrogate */
5443 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005444 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005445 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005446 /* integer overflow */
5447 PyErr_NoMemory();
5448 goto error;
5449 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005450 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005451 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005452 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005453 }
5454
5455 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005456 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005457 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005458 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005459 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005460 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5461 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005462 }
5463
5464 Py_CLEAR(rep);
5465 }
5466
5467 /* Cut back to size actually needed. This is necessary for, for example,
5468 encoding of a string containing isolated surrogates and the 'ignore'
5469 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005470 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005471 if (nsize != PyBytes_GET_SIZE(v))
5472 _PyBytes_Resize(&v, nsize);
5473 Py_XDECREF(errorHandler);
5474 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005475 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005476 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005477 error:
5478 Py_XDECREF(rep);
5479 Py_XDECREF(errorHandler);
5480 Py_XDECREF(exc);
5481 Py_XDECREF(v);
5482 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005483}
5484
Alexander Belopolsky40018472011-02-26 01:02:56 +00005485PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005486PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5487 Py_ssize_t size,
5488 const char *errors,
5489 int byteorder)
5490{
5491 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005492 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005493 if (tmp == NULL)
5494 return NULL;
5495 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5496 Py_DECREF(tmp);
5497 return result;
5498}
5499
5500PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005501PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005502{
Victor Stinnerb960b342011-11-20 19:12:52 +01005503 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005504}
5505
Guido van Rossumd57fd912000-03-10 22:53:23 +00005506/* --- UTF-16 Codec ------------------------------------------------------- */
5507
Tim Peters772747b2001-08-09 22:21:55 +00005508PyObject *
5509PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005510 Py_ssize_t size,
5511 const char *errors,
5512 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005513{
Walter Dörwald69652032004-09-07 20:24:22 +00005514 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5515}
5516
5517PyObject *
5518PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005519 Py_ssize_t size,
5520 const char *errors,
5521 int *byteorder,
5522 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005523{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005524 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005525 Py_ssize_t startinpos;
5526 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005527 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005528 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005529 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005530 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005531 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005532 PyObject *errorHandler = NULL;
5533 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005534 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005535
Tim Peters772747b2001-08-09 22:21:55 +00005536 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005537 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005538
5539 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005540 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005541
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005542 /* Check for BOM marks (U+FEFF) in the input and adjust current
5543 byte order setting accordingly. In native mode, the leading BOM
5544 mark is skipped, in all other modes, it is copied to the output
5545 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005546 if (bo == 0 && size >= 2) {
5547 const Py_UCS4 bom = (q[1] << 8) | q[0];
5548 if (bom == 0xFEFF) {
5549 q += 2;
5550 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005551 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005552 else if (bom == 0xFFFE) {
5553 q += 2;
5554 bo = 1;
5555 }
5556 if (byteorder)
5557 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005558 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559
Antoine Pitrou63065d72012-05-15 23:48:04 +02005560 if (q == e) {
5561 if (consumed)
5562 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005563 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005564 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005565
Christian Heimes743e0cd2012-10-17 23:52:17 +02005566#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005567 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005568 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005569#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005570 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005571 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005572#endif
Tim Peters772747b2001-08-09 22:21:55 +00005573
Antoine Pitrou63065d72012-05-15 23:48:04 +02005574 /* Note: size will always be longer than the resulting Unicode
5575 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005576 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005577 writer.min_length = (e - q + 1) / 2;
5578 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005579 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005580
Antoine Pitrou63065d72012-05-15 23:48:04 +02005581 while (1) {
5582 Py_UCS4 ch = 0;
5583 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005584 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005585 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005586 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005587 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005588 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005589 native_ordering);
5590 else
5591 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005592 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005593 native_ordering);
5594 } else if (kind == PyUnicode_2BYTE_KIND) {
5595 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005596 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005597 native_ordering);
5598 } else {
5599 assert(kind == PyUnicode_4BYTE_KIND);
5600 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005601 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005602 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005603 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005604 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005605
Antoine Pitrou63065d72012-05-15 23:48:04 +02005606 switch (ch)
5607 {
5608 case 0:
5609 /* remaining byte at the end? (size should be even) */
5610 if (q == e || consumed)
5611 goto End;
5612 errmsg = "truncated data";
5613 startinpos = ((const char *)q) - starts;
5614 endinpos = ((const char *)e) - starts;
5615 break;
5616 /* The remaining input chars are ignored if the callback
5617 chooses to skip the input */
5618 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005619 q -= 2;
5620 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005621 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005622 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005623 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005624 endinpos = ((const char *)e) - starts;
5625 break;
5626 case 2:
5627 errmsg = "illegal encoding";
5628 startinpos = ((const char *)q) - 2 - starts;
5629 endinpos = startinpos + 2;
5630 break;
5631 case 3:
5632 errmsg = "illegal UTF-16 surrogate";
5633 startinpos = ((const char *)q) - 4 - starts;
5634 endinpos = startinpos + 2;
5635 break;
5636 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005637 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005638 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005639 continue;
5640 }
5641
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005642 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005643 errors,
5644 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005645 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005646 &starts,
5647 (const char **)&e,
5648 &startinpos,
5649 &endinpos,
5650 &exc,
5651 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005652 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005653 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005654 }
5655
Antoine Pitrou63065d72012-05-15 23:48:04 +02005656End:
Walter Dörwald69652032004-09-07 20:24:22 +00005657 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005658 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005659
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005660 Py_XDECREF(errorHandler);
5661 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005662 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663
Benjamin Peterson29060642009-01-31 22:14:21 +00005664 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005665 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005666 Py_XDECREF(errorHandler);
5667 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 return NULL;
5669}
5670
Tim Peters772747b2001-08-09 22:21:55 +00005671PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005672_PyUnicode_EncodeUTF16(PyObject *str,
5673 const char *errors,
5674 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005676 enum PyUnicode_Kind kind;
5677 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005678 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005679 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005680 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005681 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005682#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005683 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005684#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005685 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005686#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005687 const char *encoding;
5688 Py_ssize_t nsize, pos;
5689 PyObject *errorHandler = NULL;
5690 PyObject *exc = NULL;
5691 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005692
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005693 if (!PyUnicode_Check(str)) {
5694 PyErr_BadArgument();
5695 return NULL;
5696 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005697 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005698 return NULL;
5699 kind = PyUnicode_KIND(str);
5700 data = PyUnicode_DATA(str);
5701 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005702
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005703 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005704 if (kind == PyUnicode_4BYTE_KIND) {
5705 const Py_UCS4 *in = (const Py_UCS4 *)data;
5706 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005707 while (in < end) {
5708 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005709 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005710 }
5711 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005712 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005713 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005714 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005715 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005716 nsize = len + pairs + (byteorder == 0);
5717 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005718 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005719 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005720 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005721
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005722 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005723 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005724 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005725 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005726 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005727 }
5728 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005729 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005730 }
Tim Peters772747b2001-08-09 22:21:55 +00005731
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005732 if (kind == PyUnicode_1BYTE_KIND) {
5733 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5734 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005735 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005736
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005737 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005738 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005739 }
5740 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005741 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005742 }
5743 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005744 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005745 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005746
5747 pos = 0;
5748 while (pos < len) {
5749 Py_ssize_t repsize, moreunits;
5750
5751 if (kind == PyUnicode_2BYTE_KIND) {
5752 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5753 &out, native_ordering);
5754 }
5755 else {
5756 assert(kind == PyUnicode_4BYTE_KIND);
5757 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5758 &out, native_ordering);
5759 }
5760 if (pos == len)
5761 break;
5762
5763 rep = unicode_encode_call_errorhandler(
5764 errors, &errorHandler,
5765 encoding, "surrogates not allowed",
5766 str, &exc, pos, pos + 1, &pos);
5767 if (!rep)
5768 goto error;
5769
5770 if (PyBytes_Check(rep)) {
5771 repsize = PyBytes_GET_SIZE(rep);
5772 if (repsize & 1) {
5773 raise_encode_exception(&exc, encoding,
5774 str, pos - 1, pos,
5775 "surrogates not allowed");
5776 goto error;
5777 }
5778 moreunits = repsize / 2;
5779 }
5780 else {
5781 assert(PyUnicode_Check(rep));
5782 if (PyUnicode_READY(rep) < 0)
5783 goto error;
5784 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5785 if (!PyUnicode_IS_ASCII(rep)) {
5786 raise_encode_exception(&exc, encoding,
5787 str, pos - 1, pos,
5788 "surrogates not allowed");
5789 goto error;
5790 }
5791 }
5792
5793 /* two bytes are reserved for each surrogate */
5794 if (moreunits > 1) {
5795 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005796 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005797 /* integer overflow */
5798 PyErr_NoMemory();
5799 goto error;
5800 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005801 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005802 goto error;
5803 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5804 }
5805
5806 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005807 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005808 out += moreunits;
5809 } else /* rep is unicode */ {
5810 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5811 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5812 &out, native_ordering);
5813 }
5814
5815 Py_CLEAR(rep);
5816 }
5817
5818 /* Cut back to size actually needed. This is necessary for, for example,
5819 encoding of a string containing isolated surrogates and the 'ignore' handler
5820 is used. */
5821 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5822 if (nsize != PyBytes_GET_SIZE(v))
5823 _PyBytes_Resize(&v, nsize);
5824 Py_XDECREF(errorHandler);
5825 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005826 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005827 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005828 error:
5829 Py_XDECREF(rep);
5830 Py_XDECREF(errorHandler);
5831 Py_XDECREF(exc);
5832 Py_XDECREF(v);
5833 return NULL;
5834#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005835}
5836
Alexander Belopolsky40018472011-02-26 01:02:56 +00005837PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005838PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5839 Py_ssize_t size,
5840 const char *errors,
5841 int byteorder)
5842{
5843 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005844 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005845 if (tmp == NULL)
5846 return NULL;
5847 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5848 Py_DECREF(tmp);
5849 return result;
5850}
5851
5852PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005853PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005854{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005855 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856}
5857
5858/* --- Unicode Escape Codec ----------------------------------------------- */
5859
Fredrik Lundh06d12682001-01-24 07:59:11 +00005860static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005861
Alexander Belopolsky40018472011-02-26 01:02:56 +00005862PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005863_PyUnicode_DecodeUnicodeEscape(const char *s,
5864 Py_ssize_t size,
5865 const char *errors,
5866 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005867{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005868 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005869 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871 PyObject *errorHandler = NULL;
5872 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005873
Eric V. Smith42454af2016-10-31 09:22:08 -04005874 // so we can remember if we've seen an invalid escape char or not
5875 *first_invalid_escape = NULL;
5876
Victor Stinner62ec3312016-09-06 17:04:34 -07005877 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005878 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005879 }
5880 /* Escaped strings will always be longer than the resulting
5881 Unicode string, so we start with size here and then reduce the
5882 length after conversion to the true value.
5883 (but if the error callback returns a long replacement string
5884 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005885 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005886 writer.min_length = size;
5887 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5888 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005889 }
5890
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891 end = s + size;
5892 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005893 unsigned char c = (unsigned char) *s++;
5894 Py_UCS4 ch;
5895 int count;
5896 Py_ssize_t startinpos;
5897 Py_ssize_t endinpos;
5898 const char *message;
5899
5900#define WRITE_ASCII_CHAR(ch) \
5901 do { \
5902 assert(ch <= 127); \
5903 assert(writer.pos < writer.size); \
5904 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5905 } while(0)
5906
5907#define WRITE_CHAR(ch) \
5908 do { \
5909 if (ch <= writer.maxchar) { \
5910 assert(writer.pos < writer.size); \
5911 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5912 } \
5913 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5914 goto onError; \
5915 } \
5916 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917
5918 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005919 if (c != '\\') {
5920 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005921 continue;
5922 }
5923
Victor Stinner62ec3312016-09-06 17:04:34 -07005924 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005926 if (s >= end) {
5927 message = "\\ at end of string";
5928 goto error;
5929 }
5930 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005931
Victor Stinner62ec3312016-09-06 17:04:34 -07005932 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005933 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005934
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005936 case '\n': continue;
5937 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5938 case '\'': WRITE_ASCII_CHAR('\''); continue;
5939 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5940 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005941 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005942 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5943 case 't': WRITE_ASCII_CHAR('\t'); continue;
5944 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5945 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005946 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005947 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005948 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005949 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952 case '0': case '1': case '2': case '3':
5953 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005954 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005955 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005956 ch = (ch<<3) + *s++ - '0';
5957 if (s < end && '0' <= *s && *s <= '7') {
5958 ch = (ch<<3) + *s++ - '0';
5959 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005961 WRITE_CHAR(ch);
5962 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005963
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 /* hex escapes */
5965 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005967 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005968 message = "truncated \\xXX escape";
5969 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970
Benjamin Peterson29060642009-01-31 22:14:21 +00005971 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005973 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005974 message = "truncated \\uXXXX escape";
5975 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976
Benjamin Peterson29060642009-01-31 22:14:21 +00005977 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005978 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005979 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005980 message = "truncated \\UXXXXXXXX escape";
5981 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005982 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005983 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07005984 ch <<= 4;
5985 if (c >= '0' && c <= '9') {
5986 ch += c - '0';
5987 }
5988 else if (c >= 'a' && c <= 'f') {
5989 ch += c - ('a' - 10);
5990 }
5991 else if (c >= 'A' && c <= 'F') {
5992 ch += c - ('A' - 10);
5993 }
5994 else {
5995 break;
5996 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00005997 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005998 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005999 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006000 }
6001
6002 /* when we get here, ch is a 32-bit unicode character */
6003 if (ch > MAX_UNICODE) {
6004 message = "illegal Unicode character";
6005 goto error;
6006 }
6007
6008 WRITE_CHAR(ch);
6009 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006010
Benjamin Peterson29060642009-01-31 22:14:21 +00006011 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006012 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006013 if (ucnhash_CAPI == NULL) {
6014 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006015 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6016 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006017 if (ucnhash_CAPI == NULL) {
6018 PyErr_SetString(
6019 PyExc_UnicodeError,
6020 "\\N escapes not supported (can't load unicodedata module)"
6021 );
6022 goto onError;
6023 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006024 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006025
6026 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006027 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006028 const char *start = ++s;
6029 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006030 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006031 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006032 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006033 namelen = s - start;
6034 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006035 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006036 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006037 ch = 0xffffffff; /* in case 'getcode' messes up */
6038 if (namelen <= INT_MAX &&
6039 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6040 &ch, 0)) {
6041 assert(ch <= MAX_UNICODE);
6042 WRITE_CHAR(ch);
6043 continue;
6044 }
6045 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006046 }
6047 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006048 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006049
6050 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006051 if (*first_invalid_escape == NULL) {
6052 *first_invalid_escape = s-1; /* Back up one char, since we've
6053 already incremented s. */
6054 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006055 WRITE_ASCII_CHAR('\\');
6056 WRITE_CHAR(c);
6057 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006059
6060 error:
6061 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006062 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006063 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006064 errors, &errorHandler,
6065 "unicodeescape", message,
6066 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006067 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006068 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006069 }
6070 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6071 goto onError;
6072 }
6073
6074#undef WRITE_ASCII_CHAR
6075#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006077
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006078 Py_XDECREF(errorHandler);
6079 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006080 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006081
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006083 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006084 Py_XDECREF(errorHandler);
6085 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086 return NULL;
6087}
6088
Eric V. Smith42454af2016-10-31 09:22:08 -04006089PyObject *
6090PyUnicode_DecodeUnicodeEscape(const char *s,
6091 Py_ssize_t size,
6092 const char *errors)
6093{
6094 const char *first_invalid_escape;
6095 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6096 &first_invalid_escape);
6097 if (result == NULL)
6098 return NULL;
6099 if (first_invalid_escape != NULL) {
6100 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6101 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006102 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006103 Py_DECREF(result);
6104 return NULL;
6105 }
6106 }
6107 return result;
6108}
6109
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006110/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006111
Alexander Belopolsky40018472011-02-26 01:02:56 +00006112PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006113PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006114{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006115 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006116 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006117 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006118 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006120 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121
Ezio Melottie7f90372012-10-05 03:33:31 +03006122 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006123 escape.
6124
Ezio Melottie7f90372012-10-05 03:33:31 +03006125 For UCS1 strings it's '\xxx', 4 bytes per source character.
6126 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6127 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006128 */
6129
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006130 if (!PyUnicode_Check(unicode)) {
6131 PyErr_BadArgument();
6132 return NULL;
6133 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006134 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006135 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006136 }
Victor Stinner358af132015-10-12 22:36:57 +02006137
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006138 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006139 if (len == 0) {
6140 return PyBytes_FromStringAndSize(NULL, 0);
6141 }
6142
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006143 kind = PyUnicode_KIND(unicode);
6144 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006145 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6146 bytes, and 1 byte characters 4. */
6147 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006148 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006149 return PyErr_NoMemory();
6150 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006151 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006152 if (repr == NULL) {
6153 return NULL;
6154 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006155
Victor Stinner62ec3312016-09-06 17:04:34 -07006156 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006158 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006159
Victor Stinner62ec3312016-09-06 17:04:34 -07006160 /* U+0000-U+00ff range */
6161 if (ch < 0x100) {
6162 if (ch >= ' ' && ch < 127) {
6163 if (ch != '\\') {
6164 /* Copy printable US ASCII as-is */
6165 *p++ = (char) ch;
6166 }
6167 /* Escape backslashes */
6168 else {
6169 *p++ = '\\';
6170 *p++ = '\\';
6171 }
6172 }
Victor Stinner358af132015-10-12 22:36:57 +02006173
Victor Stinner62ec3312016-09-06 17:04:34 -07006174 /* Map special whitespace to '\t', \n', '\r' */
6175 else if (ch == '\t') {
6176 *p++ = '\\';
6177 *p++ = 't';
6178 }
6179 else if (ch == '\n') {
6180 *p++ = '\\';
6181 *p++ = 'n';
6182 }
6183 else if (ch == '\r') {
6184 *p++ = '\\';
6185 *p++ = 'r';
6186 }
6187
6188 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6189 else {
6190 *p++ = '\\';
6191 *p++ = 'x';
6192 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6193 *p++ = Py_hexdigits[ch & 0x000F];
6194 }
Tim Petersced69f82003-09-16 20:30:58 +00006195 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006196 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006197 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198 *p++ = '\\';
6199 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006200 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6201 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6202 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6203 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006204 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006205 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6206 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006207
Victor Stinner62ec3312016-09-06 17:04:34 -07006208 /* Make sure that the first two digits are zero */
6209 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006210 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006211 *p++ = 'U';
6212 *p++ = '0';
6213 *p++ = '0';
6214 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6215 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6216 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6217 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6218 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6219 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006220 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222
Victor Stinner62ec3312016-09-06 17:04:34 -07006223 assert(p - PyBytes_AS_STRING(repr) > 0);
6224 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6225 return NULL;
6226 }
6227 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228}
6229
Alexander Belopolsky40018472011-02-26 01:02:56 +00006230PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006231PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6232 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006234 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006235 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006236 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006238 }
6239
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006240 result = PyUnicode_AsUnicodeEscapeString(tmp);
6241 Py_DECREF(tmp);
6242 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243}
6244
6245/* --- Raw Unicode Escape Codec ------------------------------------------- */
6246
Alexander Belopolsky40018472011-02-26 01:02:56 +00006247PyObject *
6248PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006249 Py_ssize_t size,
6250 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006251{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006252 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006253 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006255 PyObject *errorHandler = NULL;
6256 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006257
Victor Stinner62ec3312016-09-06 17:04:34 -07006258 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006259 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006260 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006261
Guido van Rossumd57fd912000-03-10 22:53:23 +00006262 /* Escaped strings will always be longer than the resulting
6263 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006264 length after conversion to the true value. (But decoding error
6265 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006266 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006267 writer.min_length = size;
6268 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6269 goto onError;
6270 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006271
Guido van Rossumd57fd912000-03-10 22:53:23 +00006272 end = s + size;
6273 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006274 unsigned char c = (unsigned char) *s++;
6275 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006276 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006277 Py_ssize_t startinpos;
6278 Py_ssize_t endinpos;
6279 const char *message;
6280
6281#define WRITE_CHAR(ch) \
6282 do { \
6283 if (ch <= writer.maxchar) { \
6284 assert(writer.pos < writer.size); \
6285 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6286 } \
6287 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6288 goto onError; \
6289 } \
6290 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006293 if (c != '\\' || s >= end) {
6294 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006296 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006297
Victor Stinner62ec3312016-09-06 17:04:34 -07006298 c = (unsigned char) *s++;
6299 if (c == 'u') {
6300 count = 4;
6301 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006302 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006303 else if (c == 'U') {
6304 count = 8;
6305 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006306 }
6307 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006308 assert(writer.pos < writer.size);
6309 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6310 WRITE_CHAR(c);
6311 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006312 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006313 startinpos = s - starts - 2;
6314
6315 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6316 for (ch = 0; count && s < end; ++s, --count) {
6317 c = (unsigned char)*s;
6318 ch <<= 4;
6319 if (c >= '0' && c <= '9') {
6320 ch += c - '0';
6321 }
6322 else if (c >= 'a' && c <= 'f') {
6323 ch += c - ('a' - 10);
6324 }
6325 else if (c >= 'A' && c <= 'F') {
6326 ch += c - ('A' - 10);
6327 }
6328 else {
6329 break;
6330 }
6331 }
6332 if (!count) {
6333 if (ch <= MAX_UNICODE) {
6334 WRITE_CHAR(ch);
6335 continue;
6336 }
6337 message = "\\Uxxxxxxxx out of range";
6338 }
6339
6340 endinpos = s-starts;
6341 writer.min_length = end - s + writer.pos;
6342 if (unicode_decode_call_errorhandler_writer(
6343 errors, &errorHandler,
6344 "rawunicodeescape", message,
6345 &starts, &end, &startinpos, &endinpos, &exc, &s,
6346 &writer)) {
6347 goto onError;
6348 }
6349 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6350 goto onError;
6351 }
6352
6353#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006355 Py_XDECREF(errorHandler);
6356 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006357 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006358
Benjamin Peterson29060642009-01-31 22:14:21 +00006359 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006360 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006361 Py_XDECREF(errorHandler);
6362 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006363 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006364
Guido van Rossumd57fd912000-03-10 22:53:23 +00006365}
6366
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006367
Alexander Belopolsky40018472011-02-26 01:02:56 +00006368PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006369PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006370{
Victor Stinner62ec3312016-09-06 17:04:34 -07006371 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006372 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006373 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006374 int kind;
6375 void *data;
6376 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006377
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006378 if (!PyUnicode_Check(unicode)) {
6379 PyErr_BadArgument();
6380 return NULL;
6381 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006382 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006383 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006384 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006385 kind = PyUnicode_KIND(unicode);
6386 data = PyUnicode_DATA(unicode);
6387 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006388 if (kind == PyUnicode_1BYTE_KIND) {
6389 return PyBytes_FromStringAndSize(data, len);
6390 }
Victor Stinner0e368262011-11-10 20:12:49 +01006391
Victor Stinner62ec3312016-09-06 17:04:34 -07006392 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6393 bytes, and 1 byte characters 4. */
6394 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006395
Victor Stinner62ec3312016-09-06 17:04:34 -07006396 if (len > PY_SSIZE_T_MAX / expandsize) {
6397 return PyErr_NoMemory();
6398 }
6399 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6400 if (repr == NULL) {
6401 return NULL;
6402 }
6403 if (len == 0) {
6404 return repr;
6405 }
6406
6407 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006408 for (pos = 0; pos < len; pos++) {
6409 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006410
Victor Stinner62ec3312016-09-06 17:04:34 -07006411 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6412 if (ch < 0x100) {
6413 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006414 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006415 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6416 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006417 *p++ = '\\';
6418 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006419 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6420 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6421 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6422 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006423 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006424 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6425 else {
6426 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6427 *p++ = '\\';
6428 *p++ = 'U';
6429 *p++ = '0';
6430 *p++ = '0';
6431 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6432 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6433 *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];
6437 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006438 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006439
Victor Stinner62ec3312016-09-06 17:04:34 -07006440 assert(p > PyBytes_AS_STRING(repr));
6441 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6442 return NULL;
6443 }
6444 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006445}
6446
Alexander Belopolsky40018472011-02-26 01:02:56 +00006447PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006448PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6449 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006450{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006451 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006452 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006453 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006454 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006455 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6456 Py_DECREF(tmp);
6457 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006458}
6459
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006460/* --- Unicode Internal Codec ------------------------------------------- */
6461
Alexander Belopolsky40018472011-02-26 01:02:56 +00006462PyObject *
6463_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006464 Py_ssize_t size,
6465 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006466{
6467 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006468 Py_ssize_t startinpos;
6469 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006470 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006471 const char *end;
6472 const char *reason;
6473 PyObject *errorHandler = NULL;
6474 PyObject *exc = NULL;
6475
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006476 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006477 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006478 1))
6479 return NULL;
6480
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006481 if (size < 0) {
6482 PyErr_BadInternalCall();
6483 return NULL;
6484 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006485 if (size == 0)
6486 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006487
Victor Stinner8f674cc2013-04-17 23:02:17 +02006488 _PyUnicodeWriter_Init(&writer);
6489 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6490 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006491 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006492 }
6493 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006494
Victor Stinner8f674cc2013-04-17 23:02:17 +02006495 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006496 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006497 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006498 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006499 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006500 endinpos = end-starts;
6501 reason = "truncated input";
6502 goto error;
6503 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006504 /* We copy the raw representation one byte at a time because the
6505 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006506 ((char *) &uch)[0] = s[0];
6507 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006508#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006509 ((char *) &uch)[2] = s[2];
6510 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006511#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006512 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006513#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006514 /* We have to sanity check the raw data, otherwise doom looms for
6515 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006516 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006517 endinpos = s - starts + Py_UNICODE_SIZE;
6518 reason = "illegal code point (> 0x10FFFF)";
6519 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006520 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006521#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006522 s += Py_UNICODE_SIZE;
6523#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006524 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006525 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006526 Py_UNICODE uch2;
6527 ((char *) &uch2)[0] = s[0];
6528 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006529 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006530 {
Victor Stinner551ac952011-11-29 22:58:13 +01006531 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006532 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006533 }
6534 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006535#endif
6536
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006537 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006538 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006539 continue;
6540
6541 error:
6542 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006543 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006544 errors, &errorHandler,
6545 "unicode_internal", reason,
6546 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006547 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006548 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006549 }
6550
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006551 Py_XDECREF(errorHandler);
6552 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006553 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006554
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006556 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006557 Py_XDECREF(errorHandler);
6558 Py_XDECREF(exc);
6559 return NULL;
6560}
6561
Guido van Rossumd57fd912000-03-10 22:53:23 +00006562/* --- Latin-1 Codec ------------------------------------------------------ */
6563
Alexander Belopolsky40018472011-02-26 01:02:56 +00006564PyObject *
6565PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006566 Py_ssize_t size,
6567 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006568{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006569 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006570 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006571}
6572
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006573/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006574static void
6575make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006576 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006577 PyObject *unicode,
6578 Py_ssize_t startpos, Py_ssize_t endpos,
6579 const char *reason)
6580{
6581 if (*exceptionObject == NULL) {
6582 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006583 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006584 encoding, unicode, startpos, endpos, reason);
6585 }
6586 else {
6587 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6588 goto onError;
6589 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6590 goto onError;
6591 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6592 goto onError;
6593 return;
6594 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006595 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006596 }
6597}
6598
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006600static void
6601raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006602 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006603 PyObject *unicode,
6604 Py_ssize_t startpos, Py_ssize_t endpos,
6605 const char *reason)
6606{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006607 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006608 encoding, unicode, startpos, endpos, reason);
6609 if (*exceptionObject != NULL)
6610 PyCodec_StrictErrors(*exceptionObject);
6611}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006612
6613/* error handling callback helper:
6614 build arguments, call the callback and check the arguments,
6615 put the result into newpos and return the replacement string, which
6616 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006617static PyObject *
6618unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006619 PyObject **errorHandler,
6620 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006622 Py_ssize_t startpos, Py_ssize_t endpos,
6623 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006624{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006625 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006626 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006627 PyObject *restuple;
6628 PyObject *resunicode;
6629
6630 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006631 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006632 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634 }
6635
Benjamin Petersonbac79492012-01-14 13:34:47 -05006636 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 return NULL;
6638 len = PyUnicode_GET_LENGTH(unicode);
6639
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006640 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006641 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006643 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006645 restuple = PyObject_CallFunctionObjArgs(
6646 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006650 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006651 Py_DECREF(restuple);
6652 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006654 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006655 &resunicode, newpos)) {
6656 Py_DECREF(restuple);
6657 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006658 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006659 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6660 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6661 Py_DECREF(restuple);
6662 return NULL;
6663 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006664 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006665 *newpos = len + *newpos;
6666 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006667 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006668 Py_DECREF(restuple);
6669 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006670 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006671 Py_INCREF(resunicode);
6672 Py_DECREF(restuple);
6673 return resunicode;
6674}
6675
Alexander Belopolsky40018472011-02-26 01:02:56 +00006676static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006677unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006678 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006679 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006680{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006681 /* input state */
6682 Py_ssize_t pos=0, size;
6683 int kind;
6684 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006685 /* pointer into the output */
6686 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006687 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6688 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006689 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006690 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006691 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006692 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006693 /* output object */
6694 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695
Benjamin Petersonbac79492012-01-14 13:34:47 -05006696 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006697 return NULL;
6698 size = PyUnicode_GET_LENGTH(unicode);
6699 kind = PyUnicode_KIND(unicode);
6700 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006701 /* allocate enough for a simple encoding without
6702 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006703 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006704 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006705
6706 _PyBytesWriter_Init(&writer);
6707 str = _PyBytesWriter_Alloc(&writer, size);
6708 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006709 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006710
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006711 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006712 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006713
Benjamin Peterson29060642009-01-31 22:14:21 +00006714 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006715 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006717 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006718 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006719 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006721 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006723 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006724 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006726
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006727 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006729
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006730 /* Only overallocate the buffer if it's not the last write */
6731 writer.overallocate = (collend < size);
6732
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006734 if (error_handler == _Py_ERROR_UNKNOWN)
6735 error_handler = get_error_handler(errors);
6736
6737 switch (error_handler) {
6738 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006739 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006741
6742 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006743 memset(str, '?', collend - collstart);
6744 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006745 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006746 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006747 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 break;
Victor Stinner50149202015-09-22 00:26:54 +02006749
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006750 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006751 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006752 writer.min_size -= (collend - collstart);
6753 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006754 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006755 if (str == NULL)
6756 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006757 pos = collend;
6758 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006759
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006760 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006761 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006762 writer.min_size -= (collend - collstart);
6763 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006764 unicode, collstart, collend);
6765 if (str == NULL)
6766 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006767 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 break;
Victor Stinner50149202015-09-22 00:26:54 +02006769
Victor Stinnerc3713e92015-09-29 12:32:13 +02006770 case _Py_ERROR_SURROGATEESCAPE:
6771 for (i = collstart; i < collend; ++i) {
6772 ch = PyUnicode_READ(kind, data, i);
6773 if (ch < 0xdc80 || 0xdcff < ch) {
6774 /* Not a UTF-8b surrogate */
6775 break;
6776 }
6777 *str++ = (char)(ch - 0xdc00);
6778 ++pos;
6779 }
6780 if (i >= collend)
6781 break;
6782 collstart = pos;
6783 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006784 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006785
Benjamin Peterson29060642009-01-31 22:14:21 +00006786 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006787 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6788 encoding, reason, unicode, &exc,
6789 collstart, collend, &newpos);
6790 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006791 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006792
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006793 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006794 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006795
Victor Stinner6bd525b2015-10-09 13:10:05 +02006796 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006797 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006798 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006799 PyBytes_AS_STRING(rep),
6800 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006801 if (str == NULL)
6802 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006803 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006804 else {
6805 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006806
Victor Stinner6bd525b2015-10-09 13:10:05 +02006807 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006808 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006809
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006810 if (limit == 256 ?
6811 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6812 !PyUnicode_IS_ASCII(rep))
6813 {
6814 /* Not all characters are smaller than limit */
6815 raise_encode_exception(&exc, encoding, unicode,
6816 collstart, collend, reason);
6817 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006818 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006819 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6820 str = _PyBytesWriter_WriteBytes(&writer, str,
6821 PyUnicode_DATA(rep),
6822 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006823 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006824 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006825 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006826 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006827
6828 /* If overallocation was disabled, ensure that it was the last
6829 write. Otherwise, we missed an optimization */
6830 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006831 }
6832 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006833
Victor Stinner50149202015-09-22 00:26:54 +02006834 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006835 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006836 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006837
6838 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006839 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006840 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006841 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006842 Py_XDECREF(exc);
6843 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006844}
6845
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006846/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006847PyObject *
6848PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006849 Py_ssize_t size,
6850 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006851{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006852 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006853 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006854 if (unicode == NULL)
6855 return NULL;
6856 result = unicode_encode_ucs1(unicode, errors, 256);
6857 Py_DECREF(unicode);
6858 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006859}
6860
Alexander Belopolsky40018472011-02-26 01:02:56 +00006861PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006862_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006863{
6864 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006865 PyErr_BadArgument();
6866 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006867 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006868 if (PyUnicode_READY(unicode) == -1)
6869 return NULL;
6870 /* Fast path: if it is a one-byte string, construct
6871 bytes object directly. */
6872 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6873 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6874 PyUnicode_GET_LENGTH(unicode));
6875 /* Non-Latin-1 characters present. Defer to above function to
6876 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006877 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006878}
6879
6880PyObject*
6881PyUnicode_AsLatin1String(PyObject *unicode)
6882{
6883 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006884}
6885
6886/* --- 7-bit ASCII Codec -------------------------------------------------- */
6887
Alexander Belopolsky40018472011-02-26 01:02:56 +00006888PyObject *
6889PyUnicode_DecodeASCII(const char *s,
6890 Py_ssize_t size,
6891 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006892{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006893 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006894 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006895 int kind;
6896 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006897 Py_ssize_t startinpos;
6898 Py_ssize_t endinpos;
6899 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006900 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006901 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006902 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006903 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006904
Guido van Rossumd57fd912000-03-10 22:53:23 +00006905 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006906 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006907
Guido van Rossumd57fd912000-03-10 22:53:23 +00006908 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006909 if (size == 1 && (unsigned char)s[0] < 128)
6910 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006911
Victor Stinner8f674cc2013-04-17 23:02:17 +02006912 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006913 writer.min_length = size;
6914 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006915 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006916
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006917 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006918 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006919 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006920 writer.pos = outpos;
6921 if (writer.pos == size)
6922 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006923
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006924 s += writer.pos;
6925 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006926 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006927 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006928 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006929 PyUnicode_WRITE(kind, data, writer.pos, c);
6930 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006931 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006932 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006933 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006934
6935 /* byte outsize range 0x00..0x7f: call the error handler */
6936
6937 if (error_handler == _Py_ERROR_UNKNOWN)
6938 error_handler = get_error_handler(errors);
6939
6940 switch (error_handler)
6941 {
6942 case _Py_ERROR_REPLACE:
6943 case _Py_ERROR_SURROGATEESCAPE:
6944 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006945 but we may switch to UCS2 at the first write */
6946 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6947 goto onError;
6948 kind = writer.kind;
6949 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006950
6951 if (error_handler == _Py_ERROR_REPLACE)
6952 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6953 else
6954 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6955 writer.pos++;
6956 ++s;
6957 break;
6958
6959 case _Py_ERROR_IGNORE:
6960 ++s;
6961 break;
6962
6963 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006964 startinpos = s-starts;
6965 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006966 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006967 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006968 "ascii", "ordinal not in range(128)",
6969 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006970 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006971 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006972 kind = writer.kind;
6973 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006975 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006976 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006977 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006978 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006979
Benjamin Peterson29060642009-01-31 22:14:21 +00006980 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006981 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006982 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006983 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006984 return NULL;
6985}
6986
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006987/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006988PyObject *
6989PyUnicode_EncodeASCII(const Py_UNICODE *p,
6990 Py_ssize_t size,
6991 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006992{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006993 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006994 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006995 if (unicode == NULL)
6996 return NULL;
6997 result = unicode_encode_ucs1(unicode, errors, 128);
6998 Py_DECREF(unicode);
6999 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007000}
7001
Alexander Belopolsky40018472011-02-26 01:02:56 +00007002PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007003_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007004{
7005 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007006 PyErr_BadArgument();
7007 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007008 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007009 if (PyUnicode_READY(unicode) == -1)
7010 return NULL;
7011 /* Fast path: if it is an ASCII-only string, construct bytes object
7012 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007013 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007014 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7015 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007016 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007017}
7018
7019PyObject *
7020PyUnicode_AsASCIIString(PyObject *unicode)
7021{
7022 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007023}
7024
Steve Dowercc16be82016-09-08 10:35:16 -07007025#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007026
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007027/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007028
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007029#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007030#define NEED_RETRY
7031#endif
7032
Victor Stinner3a50e702011-10-18 21:21:00 +02007033#ifndef WC_ERR_INVALID_CHARS
7034# define WC_ERR_INVALID_CHARS 0x0080
7035#endif
7036
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007037static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007038code_page_name(UINT code_page, PyObject **obj)
7039{
7040 *obj = NULL;
7041 if (code_page == CP_ACP)
7042 return "mbcs";
7043 if (code_page == CP_UTF7)
7044 return "CP_UTF7";
7045 if (code_page == CP_UTF8)
7046 return "CP_UTF8";
7047
7048 *obj = PyBytes_FromFormat("cp%u", code_page);
7049 if (*obj == NULL)
7050 return NULL;
7051 return PyBytes_AS_STRING(*obj);
7052}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053
Victor Stinner3a50e702011-10-18 21:21:00 +02007054static DWORD
7055decode_code_page_flags(UINT code_page)
7056{
7057 if (code_page == CP_UTF7) {
7058 /* The CP_UTF7 decoder only supports flags=0 */
7059 return 0;
7060 }
7061 else
7062 return MB_ERR_INVALID_CHARS;
7063}
7064
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007066 * Decode a byte string from a Windows code page into unicode object in strict
7067 * mode.
7068 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007069 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7070 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007071 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007072static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007073decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007074 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007075 const char *in,
7076 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077{
Victor Stinner3a50e702011-10-18 21:21:00 +02007078 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007079 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007080 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
7082 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 assert(insize > 0);
7084 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7085 if (outsize <= 0)
7086 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087
7088 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007089 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007090 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007091 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007092 if (*v == NULL)
7093 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095 }
7096 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007097 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007098 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007099 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007100 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007101 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102 }
7103
7104 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007105 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7106 if (outsize <= 0)
7107 goto error;
7108 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007109
Victor Stinner3a50e702011-10-18 21:21:00 +02007110error:
7111 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7112 return -2;
7113 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007114 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007115}
7116
Victor Stinner3a50e702011-10-18 21:21:00 +02007117/*
7118 * Decode a byte string from a code page into unicode object with an error
7119 * handler.
7120 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007121 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007122 * UnicodeDecodeError exception and returns -1 on error.
7123 */
7124static int
7125decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007126 PyObject **v,
7127 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007128 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007129{
7130 const char *startin = in;
7131 const char *endin = in + size;
7132 const DWORD flags = decode_code_page_flags(code_page);
7133 /* Ideally, we should get reason from FormatMessage. This is the Windows
7134 2000 English version of the message. */
7135 const char *reason = "No mapping for the Unicode character exists "
7136 "in the target code page.";
7137 /* each step cannot decode more than 1 character, but a character can be
7138 represented as a surrogate pair */
7139 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007140 int insize;
7141 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007142 PyObject *errorHandler = NULL;
7143 PyObject *exc = NULL;
7144 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007145 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007146 DWORD err;
7147 int ret = -1;
7148
7149 assert(size > 0);
7150
7151 encoding = code_page_name(code_page, &encoding_obj);
7152 if (encoding == NULL)
7153 return -1;
7154
Victor Stinner7d00cc12014-03-17 23:08:06 +01007155 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007156 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7157 UnicodeDecodeError. */
7158 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7159 if (exc != NULL) {
7160 PyCodec_StrictErrors(exc);
7161 Py_CLEAR(exc);
7162 }
7163 goto error;
7164 }
7165
7166 if (*v == NULL) {
7167 /* Create unicode object */
7168 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7169 PyErr_NoMemory();
7170 goto error;
7171 }
Victor Stinnerab595942011-12-17 04:59:06 +01007172 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007173 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 if (*v == NULL)
7175 goto error;
7176 startout = PyUnicode_AS_UNICODE(*v);
7177 }
7178 else {
7179 /* Extend unicode object */
7180 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7181 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7182 PyErr_NoMemory();
7183 goto error;
7184 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007185 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 goto error;
7187 startout = PyUnicode_AS_UNICODE(*v) + n;
7188 }
7189
7190 /* Decode the byte string character per character */
7191 out = startout;
7192 while (in < endin)
7193 {
7194 /* Decode a character */
7195 insize = 1;
7196 do
7197 {
7198 outsize = MultiByteToWideChar(code_page, flags,
7199 in, insize,
7200 buffer, Py_ARRAY_LENGTH(buffer));
7201 if (outsize > 0)
7202 break;
7203 err = GetLastError();
7204 if (err != ERROR_NO_UNICODE_TRANSLATION
7205 && err != ERROR_INSUFFICIENT_BUFFER)
7206 {
7207 PyErr_SetFromWindowsErr(0);
7208 goto error;
7209 }
7210 insize++;
7211 }
7212 /* 4=maximum length of a UTF-8 sequence */
7213 while (insize <= 4 && (in + insize) <= endin);
7214
7215 if (outsize <= 0) {
7216 Py_ssize_t startinpos, endinpos, outpos;
7217
Victor Stinner7d00cc12014-03-17 23:08:06 +01007218 /* last character in partial decode? */
7219 if (in + insize >= endin && !final)
7220 break;
7221
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 startinpos = in - startin;
7223 endinpos = startinpos + 1;
7224 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007225 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007226 errors, &errorHandler,
7227 encoding, reason,
7228 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007229 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 {
7231 goto error;
7232 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007233 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 }
7235 else {
7236 in += insize;
7237 memcpy(out, buffer, outsize * sizeof(wchar_t));
7238 out += outsize;
7239 }
7240 }
7241
7242 /* write a NUL character at the end */
7243 *out = 0;
7244
7245 /* Extend unicode object */
7246 outsize = out - startout;
7247 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007248 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007250 /* (in - startin) <= size and size is an int */
7251 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007252
7253error:
7254 Py_XDECREF(encoding_obj);
7255 Py_XDECREF(errorHandler);
7256 Py_XDECREF(exc);
7257 return ret;
7258}
7259
Victor Stinner3a50e702011-10-18 21:21:00 +02007260static PyObject *
7261decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007262 const char *s, Py_ssize_t size,
7263 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007264{
Victor Stinner76a31a62011-11-04 00:05:13 +01007265 PyObject *v = NULL;
7266 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007267
Victor Stinner3a50e702011-10-18 21:21:00 +02007268 if (code_page < 0) {
7269 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7270 return NULL;
7271 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007272 if (size < 0) {
7273 PyErr_BadInternalCall();
7274 return NULL;
7275 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007276
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007277 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007278 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007279
Victor Stinner76a31a62011-11-04 00:05:13 +01007280 do
7281 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007283 if (size > INT_MAX) {
7284 chunk_size = INT_MAX;
7285 final = 0;
7286 done = 0;
7287 }
7288 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007289#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007290 {
7291 chunk_size = (int)size;
7292 final = (consumed == NULL);
7293 done = 1;
7294 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007295
Victor Stinner76a31a62011-11-04 00:05:13 +01007296 if (chunk_size == 0 && done) {
7297 if (v != NULL)
7298 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007299 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007300 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007301
Victor Stinner76a31a62011-11-04 00:05:13 +01007302 converted = decode_code_page_strict(code_page, &v,
7303 s, chunk_size);
7304 if (converted == -2)
7305 converted = decode_code_page_errors(code_page, &v,
7306 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007307 errors, final);
7308 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007309
7310 if (converted < 0) {
7311 Py_XDECREF(v);
7312 return NULL;
7313 }
7314
7315 if (consumed)
7316 *consumed += converted;
7317
7318 s += converted;
7319 size -= converted;
7320 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007321
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007322 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007323}
7324
Alexander Belopolsky40018472011-02-26 01:02:56 +00007325PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007326PyUnicode_DecodeCodePageStateful(int code_page,
7327 const char *s,
7328 Py_ssize_t size,
7329 const char *errors,
7330 Py_ssize_t *consumed)
7331{
7332 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7333}
7334
7335PyObject *
7336PyUnicode_DecodeMBCSStateful(const char *s,
7337 Py_ssize_t size,
7338 const char *errors,
7339 Py_ssize_t *consumed)
7340{
7341 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7342}
7343
7344PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007345PyUnicode_DecodeMBCS(const char *s,
7346 Py_ssize_t size,
7347 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007348{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007349 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7350}
7351
Victor Stinner3a50e702011-10-18 21:21:00 +02007352static DWORD
7353encode_code_page_flags(UINT code_page, const char *errors)
7354{
7355 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007356 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007357 }
7358 else if (code_page == CP_UTF7) {
7359 /* CP_UTF7 only supports flags=0 */
7360 return 0;
7361 }
7362 else {
7363 if (errors != NULL && strcmp(errors, "replace") == 0)
7364 return 0;
7365 else
7366 return WC_NO_BEST_FIT_CHARS;
7367 }
7368}
7369
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007370/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007371 * Encode a Unicode string to a Windows code page into a byte string in strict
7372 * mode.
7373 *
7374 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007375 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007376 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007377static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007378encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007379 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007381{
Victor Stinner554f3f02010-06-16 23:33:54 +00007382 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007383 BOOL *pusedDefaultChar = &usedDefaultChar;
7384 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007385 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007386 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 const DWORD flags = encode_code_page_flags(code_page, NULL);
7388 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007389 /* Create a substring so that we can get the UTF-16 representation
7390 of just the slice under consideration. */
7391 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007392
Martin v. Löwis3d325192011-11-04 18:23:06 +01007393 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007394
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007396 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007397 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007398 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007399
Victor Stinner2fc507f2011-11-04 20:06:39 +01007400 substring = PyUnicode_Substring(unicode, offset, offset+len);
7401 if (substring == NULL)
7402 return -1;
7403 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7404 if (p == NULL) {
7405 Py_DECREF(substring);
7406 return -1;
7407 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007408 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007409
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007410 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007412 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007413 NULL, 0,
7414 NULL, pusedDefaultChar);
7415 if (outsize <= 0)
7416 goto error;
7417 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007418 if (pusedDefaultChar && *pusedDefaultChar) {
7419 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007421 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007422
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007424 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007426 if (*outbytes == NULL) {
7427 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007428 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007429 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007431 }
7432 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007433 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 const Py_ssize_t n = PyBytes_Size(*outbytes);
7435 if (outsize > PY_SSIZE_T_MAX - n) {
7436 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007437 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007438 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007440 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7441 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007442 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007443 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007445 }
7446
7447 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007449 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007450 out, outsize,
7451 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007452 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 if (outsize <= 0)
7454 goto error;
7455 if (pusedDefaultChar && *pusedDefaultChar)
7456 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007457 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007458
Victor Stinner3a50e702011-10-18 21:21:00 +02007459error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007460 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007461 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7462 return -2;
7463 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007464 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007465}
7466
Victor Stinner3a50e702011-10-18 21:21:00 +02007467/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007468 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007469 * error handler.
7470 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007471 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 * -1 on other error.
7473 */
7474static int
7475encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007476 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007477 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007478{
Victor Stinner3a50e702011-10-18 21:21:00 +02007479 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007480 Py_ssize_t pos = unicode_offset;
7481 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 /* Ideally, we should get reason from FormatMessage. This is the Windows
7483 2000 English version of the message. */
7484 const char *reason = "invalid character";
7485 /* 4=maximum length of a UTF-8 sequence */
7486 char buffer[4];
7487 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7488 Py_ssize_t outsize;
7489 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 PyObject *errorHandler = NULL;
7491 PyObject *exc = NULL;
7492 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007493 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007494 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007495 PyObject *rep;
7496 int ret = -1;
7497
7498 assert(insize > 0);
7499
7500 encoding = code_page_name(code_page, &encoding_obj);
7501 if (encoding == NULL)
7502 return -1;
7503
7504 if (errors == NULL || strcmp(errors, "strict") == 0) {
7505 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7506 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007507 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007508 if (exc != NULL) {
7509 PyCodec_StrictErrors(exc);
7510 Py_DECREF(exc);
7511 }
7512 Py_XDECREF(encoding_obj);
7513 return -1;
7514 }
7515
7516 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7517 pusedDefaultChar = &usedDefaultChar;
7518 else
7519 pusedDefaultChar = NULL;
7520
7521 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7522 PyErr_NoMemory();
7523 goto error;
7524 }
7525 outsize = insize * Py_ARRAY_LENGTH(buffer);
7526
7527 if (*outbytes == NULL) {
7528 /* Create string object */
7529 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7530 if (*outbytes == NULL)
7531 goto error;
7532 out = PyBytes_AS_STRING(*outbytes);
7533 }
7534 else {
7535 /* Extend string object */
7536 Py_ssize_t n = PyBytes_Size(*outbytes);
7537 if (n > PY_SSIZE_T_MAX - outsize) {
7538 PyErr_NoMemory();
7539 goto error;
7540 }
7541 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7542 goto error;
7543 out = PyBytes_AS_STRING(*outbytes) + n;
7544 }
7545
7546 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007547 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007548 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007549 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7550 wchar_t chars[2];
7551 int charsize;
7552 if (ch < 0x10000) {
7553 chars[0] = (wchar_t)ch;
7554 charsize = 1;
7555 }
7556 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007557 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7558 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007559 charsize = 2;
7560 }
7561
Victor Stinner3a50e702011-10-18 21:21:00 +02007562 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007563 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007564 buffer, Py_ARRAY_LENGTH(buffer),
7565 NULL, pusedDefaultChar);
7566 if (outsize > 0) {
7567 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7568 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007569 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007570 memcpy(out, buffer, outsize);
7571 out += outsize;
7572 continue;
7573 }
7574 }
7575 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7576 PyErr_SetFromWindowsErr(0);
7577 goto error;
7578 }
7579
Victor Stinner3a50e702011-10-18 21:21:00 +02007580 rep = unicode_encode_call_errorhandler(
7581 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007582 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007583 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007584 if (rep == NULL)
7585 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007586 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007587
7588 if (PyBytes_Check(rep)) {
7589 outsize = PyBytes_GET_SIZE(rep);
7590 if (outsize != 1) {
7591 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7592 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7593 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7594 Py_DECREF(rep);
7595 goto error;
7596 }
7597 out = PyBytes_AS_STRING(*outbytes) + offset;
7598 }
7599 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7600 out += outsize;
7601 }
7602 else {
7603 Py_ssize_t i;
7604 enum PyUnicode_Kind kind;
7605 void *data;
7606
Benjamin Petersonbac79492012-01-14 13:34:47 -05007607 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007608 Py_DECREF(rep);
7609 goto error;
7610 }
7611
7612 outsize = PyUnicode_GET_LENGTH(rep);
7613 if (outsize != 1) {
7614 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7615 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7616 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7617 Py_DECREF(rep);
7618 goto error;
7619 }
7620 out = PyBytes_AS_STRING(*outbytes) + offset;
7621 }
7622 kind = PyUnicode_KIND(rep);
7623 data = PyUnicode_DATA(rep);
7624 for (i=0; i < outsize; i++) {
7625 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7626 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007627 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007628 encoding, unicode,
7629 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007630 "unable to encode error handler result to ASCII");
7631 Py_DECREF(rep);
7632 goto error;
7633 }
7634 *out = (unsigned char)ch;
7635 out++;
7636 }
7637 }
7638 Py_DECREF(rep);
7639 }
7640 /* write a NUL byte */
7641 *out = 0;
7642 outsize = out - PyBytes_AS_STRING(*outbytes);
7643 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7644 if (_PyBytes_Resize(outbytes, outsize) < 0)
7645 goto error;
7646 ret = 0;
7647
7648error:
7649 Py_XDECREF(encoding_obj);
7650 Py_XDECREF(errorHandler);
7651 Py_XDECREF(exc);
7652 return ret;
7653}
7654
Victor Stinner3a50e702011-10-18 21:21:00 +02007655static PyObject *
7656encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007657 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 const char *errors)
7659{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007660 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007661 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007662 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007663 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007664
Victor Stinner29dacf22015-01-26 16:41:32 +01007665 if (!PyUnicode_Check(unicode)) {
7666 PyErr_BadArgument();
7667 return NULL;
7668 }
7669
Benjamin Petersonbac79492012-01-14 13:34:47 -05007670 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007671 return NULL;
7672 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007673
Victor Stinner3a50e702011-10-18 21:21:00 +02007674 if (code_page < 0) {
7675 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7676 return NULL;
7677 }
7678
Martin v. Löwis3d325192011-11-04 18:23:06 +01007679 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007680 return PyBytes_FromStringAndSize(NULL, 0);
7681
Victor Stinner7581cef2011-11-03 22:32:33 +01007682 offset = 0;
7683 do
7684 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007685#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007686 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007687 chunks. */
7688 if (len > INT_MAX/2) {
7689 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007690 done = 0;
7691 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007692 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007693#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007694 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007695 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007696 done = 1;
7697 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007698
Victor Stinner76a31a62011-11-04 00:05:13 +01007699 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007700 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007701 errors);
7702 if (ret == -2)
7703 ret = encode_code_page_errors(code_page, &outbytes,
7704 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007705 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007706 if (ret < 0) {
7707 Py_XDECREF(outbytes);
7708 return NULL;
7709 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007710
Victor Stinner7581cef2011-11-03 22:32:33 +01007711 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007712 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007713 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007714
Victor Stinner3a50e702011-10-18 21:21:00 +02007715 return outbytes;
7716}
7717
7718PyObject *
7719PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7720 Py_ssize_t size,
7721 const char *errors)
7722{
Victor Stinner7581cef2011-11-03 22:32:33 +01007723 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007724 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007725 if (unicode == NULL)
7726 return NULL;
7727 res = encode_code_page(CP_ACP, unicode, errors);
7728 Py_DECREF(unicode);
7729 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007730}
7731
7732PyObject *
7733PyUnicode_EncodeCodePage(int code_page,
7734 PyObject *unicode,
7735 const char *errors)
7736{
Victor Stinner7581cef2011-11-03 22:32:33 +01007737 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007738}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007739
Alexander Belopolsky40018472011-02-26 01:02:56 +00007740PyObject *
7741PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007742{
Victor Stinner7581cef2011-11-03 22:32:33 +01007743 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007744}
7745
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007746#undef NEED_RETRY
7747
Steve Dowercc16be82016-09-08 10:35:16 -07007748#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007749
Guido van Rossumd57fd912000-03-10 22:53:23 +00007750/* --- Character Mapping Codec -------------------------------------------- */
7751
Victor Stinnerfb161b12013-04-18 01:44:27 +02007752static int
7753charmap_decode_string(const char *s,
7754 Py_ssize_t size,
7755 PyObject *mapping,
7756 const char *errors,
7757 _PyUnicodeWriter *writer)
7758{
7759 const char *starts = s;
7760 const char *e;
7761 Py_ssize_t startinpos, endinpos;
7762 PyObject *errorHandler = NULL, *exc = NULL;
7763 Py_ssize_t maplen;
7764 enum PyUnicode_Kind mapkind;
7765 void *mapdata;
7766 Py_UCS4 x;
7767 unsigned char ch;
7768
7769 if (PyUnicode_READY(mapping) == -1)
7770 return -1;
7771
7772 maplen = PyUnicode_GET_LENGTH(mapping);
7773 mapdata = PyUnicode_DATA(mapping);
7774 mapkind = PyUnicode_KIND(mapping);
7775
7776 e = s + size;
7777
7778 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7779 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7780 * is disabled in encoding aliases, latin1 is preferred because
7781 * its implementation is faster. */
7782 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7783 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7784 Py_UCS4 maxchar = writer->maxchar;
7785
7786 assert (writer->kind == PyUnicode_1BYTE_KIND);
7787 while (s < e) {
7788 ch = *s;
7789 x = mapdata_ucs1[ch];
7790 if (x > maxchar) {
7791 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7792 goto onError;
7793 maxchar = writer->maxchar;
7794 outdata = (Py_UCS1 *)writer->data;
7795 }
7796 outdata[writer->pos] = x;
7797 writer->pos++;
7798 ++s;
7799 }
7800 return 0;
7801 }
7802
7803 while (s < e) {
7804 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7805 enum PyUnicode_Kind outkind = writer->kind;
7806 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7807 if (outkind == PyUnicode_1BYTE_KIND) {
7808 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7809 Py_UCS4 maxchar = writer->maxchar;
7810 while (s < e) {
7811 ch = *s;
7812 x = mapdata_ucs2[ch];
7813 if (x > maxchar)
7814 goto Error;
7815 outdata[writer->pos] = x;
7816 writer->pos++;
7817 ++s;
7818 }
7819 break;
7820 }
7821 else if (outkind == PyUnicode_2BYTE_KIND) {
7822 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7823 while (s < e) {
7824 ch = *s;
7825 x = mapdata_ucs2[ch];
7826 if (x == 0xFFFE)
7827 goto Error;
7828 outdata[writer->pos] = x;
7829 writer->pos++;
7830 ++s;
7831 }
7832 break;
7833 }
7834 }
7835 ch = *s;
7836
7837 if (ch < maplen)
7838 x = PyUnicode_READ(mapkind, mapdata, ch);
7839 else
7840 x = 0xfffe; /* invalid value */
7841Error:
7842 if (x == 0xfffe)
7843 {
7844 /* undefined mapping */
7845 startinpos = s-starts;
7846 endinpos = startinpos+1;
7847 if (unicode_decode_call_errorhandler_writer(
7848 errors, &errorHandler,
7849 "charmap", "character maps to <undefined>",
7850 &starts, &e, &startinpos, &endinpos, &exc, &s,
7851 writer)) {
7852 goto onError;
7853 }
7854 continue;
7855 }
7856
7857 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7858 goto onError;
7859 ++s;
7860 }
7861 Py_XDECREF(errorHandler);
7862 Py_XDECREF(exc);
7863 return 0;
7864
7865onError:
7866 Py_XDECREF(errorHandler);
7867 Py_XDECREF(exc);
7868 return -1;
7869}
7870
7871static int
7872charmap_decode_mapping(const char *s,
7873 Py_ssize_t size,
7874 PyObject *mapping,
7875 const char *errors,
7876 _PyUnicodeWriter *writer)
7877{
7878 const char *starts = s;
7879 const char *e;
7880 Py_ssize_t startinpos, endinpos;
7881 PyObject *errorHandler = NULL, *exc = NULL;
7882 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007883 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007884
7885 e = s + size;
7886
7887 while (s < e) {
7888 ch = *s;
7889
7890 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7891 key = PyLong_FromLong((long)ch);
7892 if (key == NULL)
7893 goto onError;
7894
7895 item = PyObject_GetItem(mapping, key);
7896 Py_DECREF(key);
7897 if (item == NULL) {
7898 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7899 /* No mapping found means: mapping is undefined. */
7900 PyErr_Clear();
7901 goto Undefined;
7902 } else
7903 goto onError;
7904 }
7905
7906 /* Apply mapping */
7907 if (item == Py_None)
7908 goto Undefined;
7909 if (PyLong_Check(item)) {
7910 long value = PyLong_AS_LONG(item);
7911 if (value == 0xFFFE)
7912 goto Undefined;
7913 if (value < 0 || value > MAX_UNICODE) {
7914 PyErr_Format(PyExc_TypeError,
7915 "character mapping must be in range(0x%lx)",
7916 (unsigned long)MAX_UNICODE + 1);
7917 goto onError;
7918 }
7919
7920 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7921 goto onError;
7922 }
7923 else if (PyUnicode_Check(item)) {
7924 if (PyUnicode_READY(item) == -1)
7925 goto onError;
7926 if (PyUnicode_GET_LENGTH(item) == 1) {
7927 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7928 if (value == 0xFFFE)
7929 goto Undefined;
7930 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7931 goto onError;
7932 }
7933 else {
7934 writer->overallocate = 1;
7935 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7936 goto onError;
7937 }
7938 }
7939 else {
7940 /* wrong return value */
7941 PyErr_SetString(PyExc_TypeError,
7942 "character mapping must return integer, None or str");
7943 goto onError;
7944 }
7945 Py_CLEAR(item);
7946 ++s;
7947 continue;
7948
7949Undefined:
7950 /* undefined mapping */
7951 Py_CLEAR(item);
7952 startinpos = s-starts;
7953 endinpos = startinpos+1;
7954 if (unicode_decode_call_errorhandler_writer(
7955 errors, &errorHandler,
7956 "charmap", "character maps to <undefined>",
7957 &starts, &e, &startinpos, &endinpos, &exc, &s,
7958 writer)) {
7959 goto onError;
7960 }
7961 }
7962 Py_XDECREF(errorHandler);
7963 Py_XDECREF(exc);
7964 return 0;
7965
7966onError:
7967 Py_XDECREF(item);
7968 Py_XDECREF(errorHandler);
7969 Py_XDECREF(exc);
7970 return -1;
7971}
7972
Alexander Belopolsky40018472011-02-26 01:02:56 +00007973PyObject *
7974PyUnicode_DecodeCharmap(const char *s,
7975 Py_ssize_t size,
7976 PyObject *mapping,
7977 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007978{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007979 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007980
Guido van Rossumd57fd912000-03-10 22:53:23 +00007981 /* Default to Latin-1 */
7982 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007983 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007984
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007986 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007987 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007988 writer.min_length = size;
7989 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007991
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007992 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007993 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7994 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007995 }
7996 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007997 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7998 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008000 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008001
Benjamin Peterson29060642009-01-31 22:14:21 +00008002 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008003 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008004 return NULL;
8005}
8006
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008007/* Charmap encoding: the lookup table */
8008
Alexander Belopolsky40018472011-02-26 01:02:56 +00008009struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 PyObject_HEAD
8011 unsigned char level1[32];
8012 int count2, count3;
8013 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008014};
8015
8016static PyObject*
8017encoding_map_size(PyObject *obj, PyObject* args)
8018{
8019 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008020 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008022}
8023
8024static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008025 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 PyDoc_STR("Return the size (in bytes) of this object") },
8027 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028};
8029
8030static void
8031encoding_map_dealloc(PyObject* o)
8032{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008033 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008034}
8035
8036static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008037 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 "EncodingMap", /*tp_name*/
8039 sizeof(struct encoding_map), /*tp_basicsize*/
8040 0, /*tp_itemsize*/
8041 /* methods */
8042 encoding_map_dealloc, /*tp_dealloc*/
8043 0, /*tp_print*/
8044 0, /*tp_getattr*/
8045 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008046 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008047 0, /*tp_repr*/
8048 0, /*tp_as_number*/
8049 0, /*tp_as_sequence*/
8050 0, /*tp_as_mapping*/
8051 0, /*tp_hash*/
8052 0, /*tp_call*/
8053 0, /*tp_str*/
8054 0, /*tp_getattro*/
8055 0, /*tp_setattro*/
8056 0, /*tp_as_buffer*/
8057 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8058 0, /*tp_doc*/
8059 0, /*tp_traverse*/
8060 0, /*tp_clear*/
8061 0, /*tp_richcompare*/
8062 0, /*tp_weaklistoffset*/
8063 0, /*tp_iter*/
8064 0, /*tp_iternext*/
8065 encoding_map_methods, /*tp_methods*/
8066 0, /*tp_members*/
8067 0, /*tp_getset*/
8068 0, /*tp_base*/
8069 0, /*tp_dict*/
8070 0, /*tp_descr_get*/
8071 0, /*tp_descr_set*/
8072 0, /*tp_dictoffset*/
8073 0, /*tp_init*/
8074 0, /*tp_alloc*/
8075 0, /*tp_new*/
8076 0, /*tp_free*/
8077 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078};
8079
8080PyObject*
8081PyUnicode_BuildEncodingMap(PyObject* string)
8082{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008083 PyObject *result;
8084 struct encoding_map *mresult;
8085 int i;
8086 int need_dict = 0;
8087 unsigned char level1[32];
8088 unsigned char level2[512];
8089 unsigned char *mlevel1, *mlevel2, *mlevel3;
8090 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008091 int kind;
8092 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008093 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008094 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008095
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008096 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008097 PyErr_BadArgument();
8098 return NULL;
8099 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008100 kind = PyUnicode_KIND(string);
8101 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008102 length = PyUnicode_GET_LENGTH(string);
8103 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104 memset(level1, 0xFF, sizeof level1);
8105 memset(level2, 0xFF, sizeof level2);
8106
8107 /* If there isn't a one-to-one mapping of NULL to \0,
8108 or if there are non-BMP characters, we need to use
8109 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008110 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008112 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008114 ch = PyUnicode_READ(kind, data, i);
8115 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008116 need_dict = 1;
8117 break;
8118 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008119 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008120 /* unmapped character */
8121 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008122 l1 = ch >> 11;
8123 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008124 if (level1[l1] == 0xFF)
8125 level1[l1] = count2++;
8126 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008127 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128 }
8129
8130 if (count2 >= 0xFF || count3 >= 0xFF)
8131 need_dict = 1;
8132
8133 if (need_dict) {
8134 PyObject *result = PyDict_New();
8135 PyObject *key, *value;
8136 if (!result)
8137 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008138 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008139 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008140 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008141 if (!key || !value)
8142 goto failed1;
8143 if (PyDict_SetItem(result, key, value) == -1)
8144 goto failed1;
8145 Py_DECREF(key);
8146 Py_DECREF(value);
8147 }
8148 return result;
8149 failed1:
8150 Py_XDECREF(key);
8151 Py_XDECREF(value);
8152 Py_DECREF(result);
8153 return NULL;
8154 }
8155
8156 /* Create a three-level trie */
8157 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8158 16*count2 + 128*count3 - 1);
8159 if (!result)
8160 return PyErr_NoMemory();
8161 PyObject_Init(result, &EncodingMapType);
8162 mresult = (struct encoding_map*)result;
8163 mresult->count2 = count2;
8164 mresult->count3 = count3;
8165 mlevel1 = mresult->level1;
8166 mlevel2 = mresult->level23;
8167 mlevel3 = mresult->level23 + 16*count2;
8168 memcpy(mlevel1, level1, 32);
8169 memset(mlevel2, 0xFF, 16*count2);
8170 memset(mlevel3, 0, 128*count3);
8171 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008172 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008173 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008174 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8175 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008176 /* unmapped character */
8177 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008178 o1 = ch>>11;
8179 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008180 i2 = 16*mlevel1[o1] + o2;
8181 if (mlevel2[i2] == 0xFF)
8182 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008183 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008184 i3 = 128*mlevel2[i2] + o3;
8185 mlevel3[i3] = i;
8186 }
8187 return result;
8188}
8189
8190static int
Victor Stinner22168992011-11-20 17:09:18 +01008191encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008192{
8193 struct encoding_map *map = (struct encoding_map*)mapping;
8194 int l1 = c>>11;
8195 int l2 = (c>>7) & 0xF;
8196 int l3 = c & 0x7F;
8197 int i;
8198
Victor Stinner22168992011-11-20 17:09:18 +01008199 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008200 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008201 if (c == 0)
8202 return 0;
8203 /* level 1*/
8204 i = map->level1[l1];
8205 if (i == 0xFF) {
8206 return -1;
8207 }
8208 /* level 2*/
8209 i = map->level23[16*i+l2];
8210 if (i == 0xFF) {
8211 return -1;
8212 }
8213 /* level 3 */
8214 i = map->level23[16*map->count2 + 128*i + l3];
8215 if (i == 0) {
8216 return -1;
8217 }
8218 return i;
8219}
8220
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221/* Lookup the character ch in the mapping. If the character
8222 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008223 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008224static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008225charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008226{
Christian Heimes217cfd12007-12-02 14:31:20 +00008227 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008228 PyObject *x;
8229
8230 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008231 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008232 x = PyObject_GetItem(mapping, w);
8233 Py_DECREF(w);
8234 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8236 /* No mapping found means: mapping is undefined. */
8237 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008238 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 } else
8240 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008241 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008242 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008244 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 long value = PyLong_AS_LONG(x);
8246 if (value < 0 || value > 255) {
8247 PyErr_SetString(PyExc_TypeError,
8248 "character mapping must be in range(256)");
8249 Py_DECREF(x);
8250 return NULL;
8251 }
8252 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008254 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008256 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 /* wrong return value */
8258 PyErr_Format(PyExc_TypeError,
8259 "character mapping must return integer, bytes or None, not %.400s",
8260 x->ob_type->tp_name);
8261 Py_DECREF(x);
8262 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008263 }
8264}
8265
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008266static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008267charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008268{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008269 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8270 /* exponentially overallocate to minimize reallocations */
8271 if (requiredsize < 2*outsize)
8272 requiredsize = 2*outsize;
8273 if (_PyBytes_Resize(outobj, requiredsize))
8274 return -1;
8275 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008276}
8277
Benjamin Peterson14339b62009-01-31 16:36:08 +00008278typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008280} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008282 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008283 space is available. Return a new reference to the object that
8284 was put in the output buffer, or Py_None, if the mapping was undefined
8285 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008286 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008287static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008288charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008289 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008291 PyObject *rep;
8292 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008293 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008294
Christian Heimes90aa7642007-12-19 02:45:37 +00008295 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008296 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008297 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008298 if (res == -1)
8299 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 if (outsize<requiredsize)
8301 if (charmapencode_resize(outobj, outpos, requiredsize))
8302 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008303 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 outstart[(*outpos)++] = (char)res;
8305 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008306 }
8307
8308 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008309 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008311 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 Py_DECREF(rep);
8313 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008314 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 if (PyLong_Check(rep)) {
8316 Py_ssize_t requiredsize = *outpos+1;
8317 if (outsize<requiredsize)
8318 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8319 Py_DECREF(rep);
8320 return enc_EXCEPTION;
8321 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008322 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008324 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 else {
8326 const char *repchars = PyBytes_AS_STRING(rep);
8327 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8328 Py_ssize_t requiredsize = *outpos+repsize;
8329 if (outsize<requiredsize)
8330 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8331 Py_DECREF(rep);
8332 return enc_EXCEPTION;
8333 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008334 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 memcpy(outstart + *outpos, repchars, repsize);
8336 *outpos += repsize;
8337 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008338 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008339 Py_DECREF(rep);
8340 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008341}
8342
8343/* handle an error in PyUnicode_EncodeCharmap
8344 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008345static int
8346charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008347 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008349 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008350 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351{
8352 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008353 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008354 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008355 enum PyUnicode_Kind kind;
8356 void *data;
8357 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008359 Py_ssize_t collstartpos = *inpos;
8360 Py_ssize_t collendpos = *inpos+1;
8361 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008362 const char *encoding = "charmap";
8363 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008364 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008365 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008366 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367
Benjamin Petersonbac79492012-01-14 13:34:47 -05008368 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008369 return -1;
8370 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 /* find all unencodable characters */
8372 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008373 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008374 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008375 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008376 val = encoding_map_lookup(ch, mapping);
8377 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 break;
8379 ++collendpos;
8380 continue;
8381 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008382
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008383 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8384 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 if (rep==NULL)
8386 return -1;
8387 else if (rep!=Py_None) {
8388 Py_DECREF(rep);
8389 break;
8390 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008391 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393 }
8394 /* cache callback name lookup
8395 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008396 if (*error_handler == _Py_ERROR_UNKNOWN)
8397 *error_handler = get_error_handler(errors);
8398
8399 switch (*error_handler) {
8400 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008401 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008402 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008403
8404 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008405 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 x = charmapencode_output('?', mapping, res, respos);
8407 if (x==enc_EXCEPTION) {
8408 return -1;
8409 }
8410 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008411 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 return -1;
8413 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008414 }
8415 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008416 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008417 *inpos = collendpos;
8418 break;
Victor Stinner50149202015-09-22 00:26:54 +02008419
8420 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008421 /* generate replacement (temporarily (mis)uses p) */
8422 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 char buffer[2+29+1+1];
8424 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008425 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 for (cp = buffer; *cp; ++cp) {
8427 x = charmapencode_output(*cp, mapping, res, respos);
8428 if (x==enc_EXCEPTION)
8429 return -1;
8430 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008431 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 return -1;
8433 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008434 }
8435 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008436 *inpos = collendpos;
8437 break;
Victor Stinner50149202015-09-22 00:26:54 +02008438
Benjamin Peterson14339b62009-01-31 16:36:08 +00008439 default:
Victor Stinner50149202015-09-22 00:26:54 +02008440 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008441 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008443 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008445 if (PyBytes_Check(repunicode)) {
8446 /* Directly copy bytes result to output. */
8447 Py_ssize_t outsize = PyBytes_Size(*res);
8448 Py_ssize_t requiredsize;
8449 repsize = PyBytes_Size(repunicode);
8450 requiredsize = *respos + repsize;
8451 if (requiredsize > outsize)
8452 /* Make room for all additional bytes. */
8453 if (charmapencode_resize(res, respos, requiredsize)) {
8454 Py_DECREF(repunicode);
8455 return -1;
8456 }
8457 memcpy(PyBytes_AsString(*res) + *respos,
8458 PyBytes_AsString(repunicode), repsize);
8459 *respos += repsize;
8460 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008461 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008462 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008463 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008464 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008465 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008466 Py_DECREF(repunicode);
8467 return -1;
8468 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008469 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008470 data = PyUnicode_DATA(repunicode);
8471 kind = PyUnicode_KIND(repunicode);
8472 for (index = 0; index < repsize; index++) {
8473 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8474 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008476 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 return -1;
8478 }
8479 else if (x==enc_FAILED) {
8480 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008481 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 return -1;
8483 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008484 }
8485 *inpos = newpos;
8486 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 }
8488 return 0;
8489}
8490
Alexander Belopolsky40018472011-02-26 01:02:56 +00008491PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008492_PyUnicode_EncodeCharmap(PyObject *unicode,
8493 PyObject *mapping,
8494 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008495{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 /* output object */
8497 PyObject *res = NULL;
8498 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008499 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008500 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008502 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008503 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008504 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008505 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008506 void *data;
8507 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008508
Benjamin Petersonbac79492012-01-14 13:34:47 -05008509 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008510 return NULL;
8511 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008512 data = PyUnicode_DATA(unicode);
8513 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514
Guido van Rossumd57fd912000-03-10 22:53:23 +00008515 /* Default to Latin-1 */
8516 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008517 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008519 /* allocate enough for a simple encoding without
8520 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008521 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522 if (res == NULL)
8523 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008524 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008526
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008528 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008530 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008531 if (x==enc_EXCEPTION) /* error */
8532 goto onError;
8533 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008534 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008536 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 &res, &respos)) {
8538 goto onError;
8539 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008540 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008541 else
8542 /* done with this character => adjust input position */
8543 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008544 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008545
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008546 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008547 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008548 if (_PyBytes_Resize(&res, respos) < 0)
8549 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008550
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008552 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008553 return res;
8554
Benjamin Peterson29060642009-01-31 22:14:21 +00008555 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008556 Py_XDECREF(res);
8557 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008558 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559 return NULL;
8560}
8561
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008562/* Deprecated */
8563PyObject *
8564PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8565 Py_ssize_t size,
8566 PyObject *mapping,
8567 const char *errors)
8568{
8569 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008570 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008571 if (unicode == NULL)
8572 return NULL;
8573 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8574 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008575 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008576}
8577
Alexander Belopolsky40018472011-02-26 01:02:56 +00008578PyObject *
8579PyUnicode_AsCharmapString(PyObject *unicode,
8580 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581{
8582 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008583 PyErr_BadArgument();
8584 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008585 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008586 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008587}
8588
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008589/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008590static void
8591make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008592 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008593 Py_ssize_t startpos, Py_ssize_t endpos,
8594 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008595{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597 *exceptionObject = _PyUnicodeTranslateError_Create(
8598 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008599 }
8600 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008601 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8602 goto onError;
8603 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8604 goto onError;
8605 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8606 goto onError;
8607 return;
8608 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008609 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008610 }
8611}
8612
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008613/* error handling callback helper:
8614 build arguments, call the callback and check the arguments,
8615 put the result into newpos and return the replacement string, which
8616 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008617static PyObject *
8618unicode_translate_call_errorhandler(const char *errors,
8619 PyObject **errorHandler,
8620 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008622 Py_ssize_t startpos, Py_ssize_t endpos,
8623 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008625 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008626
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008627 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 PyObject *restuple;
8629 PyObject *resunicode;
8630
8631 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008635 }
8636
8637 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008642 restuple = PyObject_CallFunctionObjArgs(
8643 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008646 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008647 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 Py_DECREF(restuple);
8649 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008651 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 &resunicode, &i_newpos)) {
8653 Py_DECREF(restuple);
8654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008656 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008658 else
8659 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008661 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 Py_DECREF(restuple);
8663 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008664 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 Py_INCREF(resunicode);
8666 Py_DECREF(restuple);
8667 return resunicode;
8668}
8669
8670/* Lookup the character ch in the mapping and put the result in result,
8671 which must be decrefed by the caller.
8672 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008673static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675{
Christian Heimes217cfd12007-12-02 14:31:20 +00008676 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677 PyObject *x;
8678
8679 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008680 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008681 x = PyObject_GetItem(mapping, w);
8682 Py_DECREF(w);
8683 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8685 /* No mapping found means: use 1:1 mapping. */
8686 PyErr_Clear();
8687 *result = NULL;
8688 return 0;
8689 } else
8690 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 }
8692 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008693 *result = x;
8694 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008695 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008696 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008698 if (value < 0 || value > MAX_UNICODE) {
8699 PyErr_Format(PyExc_ValueError,
8700 "character mapping must be in range(0x%x)",
8701 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 Py_DECREF(x);
8703 return -1;
8704 }
8705 *result = x;
8706 return 0;
8707 }
8708 else if (PyUnicode_Check(x)) {
8709 *result = x;
8710 return 0;
8711 }
8712 else {
8713 /* wrong return value */
8714 PyErr_SetString(PyExc_TypeError,
8715 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008716 Py_DECREF(x);
8717 return -1;
8718 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008719}
Victor Stinner1194ea02014-04-04 19:37:40 +02008720
8721/* lookup the character, write the result into the writer.
8722 Return 1 if the result was written into the writer, return 0 if the mapping
8723 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008724static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008725charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8726 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008727{
Victor Stinner1194ea02014-04-04 19:37:40 +02008728 PyObject *item;
8729
8730 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008731 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008732
8733 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008735 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008736 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008737 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008738 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008739 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008740
8741 if (item == Py_None) {
8742 Py_DECREF(item);
8743 return 0;
8744 }
8745
8746 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008747 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8748 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8749 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008750 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8751 Py_DECREF(item);
8752 return -1;
8753 }
8754 Py_DECREF(item);
8755 return 1;
8756 }
8757
8758 if (!PyUnicode_Check(item)) {
8759 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008760 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008761 }
8762
8763 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8764 Py_DECREF(item);
8765 return -1;
8766 }
8767
8768 Py_DECREF(item);
8769 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008770}
8771
Victor Stinner89a76ab2014-04-05 11:44:04 +02008772static int
8773unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8774 Py_UCS1 *translate)
8775{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008776 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008777 int ret = 0;
8778
Victor Stinner89a76ab2014-04-05 11:44:04 +02008779 if (charmaptranslate_lookup(ch, mapping, &item)) {
8780 return -1;
8781 }
8782
8783 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008784 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008785 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008786 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008787 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008788 /* not found => default to 1:1 mapping */
8789 translate[ch] = ch;
8790 return 1;
8791 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008792 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008793 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008794 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8795 used it */
8796 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008797 /* invalid character or character outside ASCII:
8798 skip the fast translate */
8799 goto exit;
8800 }
8801 translate[ch] = (Py_UCS1)replace;
8802 }
8803 else if (PyUnicode_Check(item)) {
8804 Py_UCS4 replace;
8805
8806 if (PyUnicode_READY(item) == -1) {
8807 Py_DECREF(item);
8808 return -1;
8809 }
8810 if (PyUnicode_GET_LENGTH(item) != 1)
8811 goto exit;
8812
8813 replace = PyUnicode_READ_CHAR(item, 0);
8814 if (replace > 127)
8815 goto exit;
8816 translate[ch] = (Py_UCS1)replace;
8817 }
8818 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008819 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008820 goto exit;
8821 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008822 ret = 1;
8823
Benjamin Peterson1365de72014-04-07 20:15:41 -04008824 exit:
8825 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008826 return ret;
8827}
8828
8829/* Fast path for ascii => ascii translation. Return 1 if the whole string
8830 was translated into writer, return 0 if the input string was partially
8831 translated into writer, raise an exception and return -1 on error. */
8832static int
8833unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008834 _PyUnicodeWriter *writer, int ignore,
8835 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008836{
Victor Stinner872b2912014-04-05 14:27:07 +02008837 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008838 Py_ssize_t len;
8839 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008840 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008841
Victor Stinner89a76ab2014-04-05 11:44:04 +02008842 len = PyUnicode_GET_LENGTH(input);
8843
Victor Stinner872b2912014-04-05 14:27:07 +02008844 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008845
8846 in = PyUnicode_1BYTE_DATA(input);
8847 end = in + len;
8848
8849 assert(PyUnicode_IS_ASCII(writer->buffer));
8850 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8851 out = PyUnicode_1BYTE_DATA(writer->buffer);
8852
Victor Stinner872b2912014-04-05 14:27:07 +02008853 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008854 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008855 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008856 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008857 int translate = unicode_fast_translate_lookup(mapping, ch,
8858 ascii_table);
8859 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008860 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008861 if (translate == 0)
8862 goto exit;
8863 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008864 }
Victor Stinner872b2912014-04-05 14:27:07 +02008865 if (ch2 == 0xfe) {
8866 if (ignore)
8867 continue;
8868 goto exit;
8869 }
8870 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008871 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008872 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008873 }
Victor Stinner872b2912014-04-05 14:27:07 +02008874 res = 1;
8875
8876exit:
8877 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008878 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008879 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008880}
8881
Victor Stinner3222da22015-10-01 22:07:32 +02008882static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008883_PyUnicode_TranslateCharmap(PyObject *input,
8884 PyObject *mapping,
8885 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008886{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008887 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008888 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008889 Py_ssize_t size, i;
8890 int kind;
8891 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008892 _PyUnicodeWriter writer;
8893 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008894 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008895 PyObject *errorHandler = NULL;
8896 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008897 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008898 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008899
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008901 PyErr_BadArgument();
8902 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008903 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008905 if (PyUnicode_READY(input) == -1)
8906 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008907 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008908 kind = PyUnicode_KIND(input);
8909 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008910
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008911 if (size == 0)
8912 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008913
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008914 /* allocate enough for a simple 1:1 translation without
8915 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008916 _PyUnicodeWriter_Init(&writer);
8917 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008918 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008919
Victor Stinner872b2912014-04-05 14:27:07 +02008920 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8921
Victor Stinner33798672016-03-01 21:59:58 +01008922 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008923 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008924 if (PyUnicode_IS_ASCII(input)) {
8925 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8926 if (res < 0) {
8927 _PyUnicodeWriter_Dealloc(&writer);
8928 return NULL;
8929 }
8930 if (res == 1)
8931 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008932 }
Victor Stinner33798672016-03-01 21:59:58 +01008933 else {
8934 i = 0;
8935 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008937 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008938 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008939 int translate;
8940 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8941 Py_ssize_t newpos;
8942 /* startpos for collecting untranslatable chars */
8943 Py_ssize_t collstart;
8944 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008945 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008946
Victor Stinner1194ea02014-04-04 19:37:40 +02008947 ch = PyUnicode_READ(kind, data, i);
8948 translate = charmaptranslate_output(ch, mapping, &writer);
8949 if (translate < 0)
8950 goto onError;
8951
8952 if (translate != 0) {
8953 /* it worked => adjust input pointer */
8954 ++i;
8955 continue;
8956 }
8957
8958 /* untranslatable character */
8959 collstart = i;
8960 collend = i+1;
8961
8962 /* find all untranslatable characters */
8963 while (collend < size) {
8964 PyObject *x;
8965 ch = PyUnicode_READ(kind, data, collend);
8966 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008967 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008968 Py_XDECREF(x);
8969 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008970 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008971 ++collend;
8972 }
8973
8974 if (ignore) {
8975 i = collend;
8976 }
8977 else {
8978 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8979 reason, input, &exc,
8980 collstart, collend, &newpos);
8981 if (repunicode == NULL)
8982 goto onError;
8983 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008984 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008985 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008986 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008987 Py_DECREF(repunicode);
8988 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008989 }
8990 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008991 Py_XDECREF(exc);
8992 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008993 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008994
Benjamin Peterson29060642009-01-31 22:14:21 +00008995 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008996 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008997 Py_XDECREF(exc);
8998 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008999 return NULL;
9000}
9001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002/* Deprecated. Use PyUnicode_Translate instead. */
9003PyObject *
9004PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9005 Py_ssize_t size,
9006 PyObject *mapping,
9007 const char *errors)
9008{
Christian Heimes5f520f42012-09-11 14:03:25 +02009009 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009010 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011 if (!unicode)
9012 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009013 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9014 Py_DECREF(unicode);
9015 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016}
9017
Alexander Belopolsky40018472011-02-26 01:02:56 +00009018PyObject *
9019PyUnicode_Translate(PyObject *str,
9020 PyObject *mapping,
9021 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009022{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009023 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009024 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009025 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009026}
Tim Petersced69f82003-09-16 20:30:58 +00009027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009028PyObject *
9029_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9030{
9031 if (!PyUnicode_Check(unicode)) {
9032 PyErr_BadInternalCall();
9033 return NULL;
9034 }
9035 if (PyUnicode_READY(unicode) == -1)
9036 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009037 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038 /* If the string is already ASCII, just return the same string */
9039 Py_INCREF(unicode);
9040 return unicode;
9041 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009042
9043 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9044 PyObject *result = PyUnicode_New(len, 127);
9045 if (result == NULL) {
9046 return NULL;
9047 }
9048
9049 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9050 int kind = PyUnicode_KIND(unicode);
9051 const void *data = PyUnicode_DATA(unicode);
9052 Py_ssize_t i;
9053 for (i = 0; i < len; ++i) {
9054 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9055 if (ch < 127) {
9056 out[i] = ch;
9057 }
9058 else if (Py_UNICODE_ISSPACE(ch)) {
9059 out[i] = ' ';
9060 }
9061 else {
9062 int decimal = Py_UNICODE_TODECIMAL(ch);
9063 if (decimal < 0) {
9064 out[i] = '?';
9065 _PyUnicode_LENGTH(result) = i + 1;
9066 break;
9067 }
9068 out[i] = '0' + decimal;
9069 }
9070 }
9071
9072 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009073}
9074
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009075PyObject *
9076PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9077 Py_ssize_t length)
9078{
Victor Stinnerf0124502011-11-21 23:12:56 +01009079 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009080 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009081 Py_UCS4 maxchar;
9082 enum PyUnicode_Kind kind;
9083 void *data;
9084
Victor Stinner99d7ad02012-02-22 13:37:39 +01009085 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009086 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009087 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009088 if (ch > 127) {
9089 int decimal = Py_UNICODE_TODECIMAL(ch);
9090 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009091 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009092 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009093 }
9094 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009095
9096 /* Copy to a new string */
9097 decimal = PyUnicode_New(length, maxchar);
9098 if (decimal == NULL)
9099 return decimal;
9100 kind = PyUnicode_KIND(decimal);
9101 data = PyUnicode_DATA(decimal);
9102 /* Iterate over code points */
9103 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009104 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009105 if (ch > 127) {
9106 int decimal = Py_UNICODE_TODECIMAL(ch);
9107 if (decimal >= 0)
9108 ch = '0' + decimal;
9109 }
9110 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009112 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009113}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009114/* --- Decimal Encoder ---------------------------------------------------- */
9115
Alexander Belopolsky40018472011-02-26 01:02:56 +00009116int
9117PyUnicode_EncodeDecimal(Py_UNICODE *s,
9118 Py_ssize_t length,
9119 char *output,
9120 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009121{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009122 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009123 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009124 enum PyUnicode_Kind kind;
9125 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009126
9127 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009128 PyErr_BadArgument();
9129 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009130 }
9131
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009132 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009133 if (unicode == NULL)
9134 return -1;
9135
Victor Stinner42bf7752011-11-21 22:52:58 +01009136 kind = PyUnicode_KIND(unicode);
9137 data = PyUnicode_DATA(unicode);
9138
Victor Stinnerb84d7232011-11-22 01:50:07 +01009139 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009140 PyObject *exc;
9141 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009143 Py_ssize_t startpos;
9144
9145 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009146
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009148 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009149 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009150 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009151 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009152 decimal = Py_UNICODE_TODECIMAL(ch);
9153 if (decimal >= 0) {
9154 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009155 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009156 continue;
9157 }
9158 if (0 < ch && ch < 256) {
9159 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009160 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 continue;
9162 }
Victor Stinner6345be92011-11-25 20:09:01 +01009163
Victor Stinner42bf7752011-11-21 22:52:58 +01009164 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009165 exc = NULL;
9166 raise_encode_exception(&exc, "decimal", unicode,
9167 startpos, startpos+1,
9168 "invalid decimal Unicode string");
9169 Py_XDECREF(exc);
9170 Py_DECREF(unicode);
9171 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009172 }
9173 /* 0-terminate the output string */
9174 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009175 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009176 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009177}
9178
Guido van Rossumd57fd912000-03-10 22:53:23 +00009179/* --- Helpers ------------------------------------------------------------ */
9180
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009181/* helper macro to fixup start/end slice values */
9182#define ADJUST_INDICES(start, end, len) \
9183 if (end > len) \
9184 end = len; \
9185 else if (end < 0) { \
9186 end += len; \
9187 if (end < 0) \
9188 end = 0; \
9189 } \
9190 if (start < 0) { \
9191 start += len; \
9192 if (start < 0) \
9193 start = 0; \
9194 }
9195
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009196static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009197any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009199 Py_ssize_t end,
9200 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009201{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009202 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 void *buf1, *buf2;
9204 Py_ssize_t len1, len2, result;
9205
9206 kind1 = PyUnicode_KIND(s1);
9207 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009208 if (kind1 < kind2)
9209 return -1;
9210
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211 len1 = PyUnicode_GET_LENGTH(s1);
9212 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009213 ADJUST_INDICES(start, end, len1);
9214 if (end - start < len2)
9215 return -1;
9216
9217 buf1 = PyUnicode_DATA(s1);
9218 buf2 = PyUnicode_DATA(s2);
9219 if (len2 == 1) {
9220 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9221 result = findchar((const char *)buf1 + kind1*start,
9222 kind1, end - start, ch, direction);
9223 if (result == -1)
9224 return -1;
9225 else
9226 return start + result;
9227 }
9228
9229 if (kind2 != kind1) {
9230 buf2 = _PyUnicode_AsKind(s2, kind1);
9231 if (!buf2)
9232 return -2;
9233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234
Victor Stinner794d5672011-10-10 03:21:36 +02009235 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009236 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009237 case PyUnicode_1BYTE_KIND:
9238 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9239 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9240 else
9241 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9242 break;
9243 case PyUnicode_2BYTE_KIND:
9244 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9245 break;
9246 case PyUnicode_4BYTE_KIND:
9247 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9248 break;
9249 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009250 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009251 }
9252 }
9253 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009254 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009255 case PyUnicode_1BYTE_KIND:
9256 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9257 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9258 else
9259 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9260 break;
9261 case PyUnicode_2BYTE_KIND:
9262 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9263 break;
9264 case PyUnicode_4BYTE_KIND:
9265 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9266 break;
9267 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009268 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009269 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270 }
9271
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009272 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009273 PyMem_Free(buf2);
9274
9275 return result;
9276}
9277
9278Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009279_PyUnicode_InsertThousandsGrouping(
9280 PyObject *unicode, Py_ssize_t index,
9281 Py_ssize_t n_buffer,
9282 void *digits, Py_ssize_t n_digits,
9283 Py_ssize_t min_width,
9284 const char *grouping, PyObject *thousands_sep,
9285 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009286{
Victor Stinner41a863c2012-02-24 00:37:51 +01009287 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009288 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009289 Py_ssize_t thousands_sep_len;
9290 Py_ssize_t len;
9291
9292 if (unicode != NULL) {
9293 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009294 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009295 }
9296 else {
9297 kind = PyUnicode_1BYTE_KIND;
9298 data = NULL;
9299 }
9300 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9301 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9302 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9303 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009304 if (thousands_sep_kind < kind) {
9305 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9306 if (!thousands_sep_data)
9307 return -1;
9308 }
9309 else {
9310 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9311 if (!data)
9312 return -1;
9313 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009314 }
9315
Benjamin Petersonead6b532011-12-20 17:23:42 -06009316 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009317 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009318 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009319 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009320 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009321 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009322 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009323 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009324 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009325 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009326 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009327 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009328 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009329 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009330 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009331 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009332 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009333 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009334 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009336 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009337 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009338 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009339 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009340 break;
9341 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009342 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009343 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009344 if (unicode != NULL && thousands_sep_kind != kind) {
9345 if (thousands_sep_kind < kind)
9346 PyMem_Free(thousands_sep_data);
9347 else
9348 PyMem_Free(data);
9349 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009350 if (unicode == NULL) {
9351 *maxchar = 127;
9352 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009353 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009354 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009355 }
9356 }
9357 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009358}
9359
9360
Alexander Belopolsky40018472011-02-26 01:02:56 +00009361Py_ssize_t
9362PyUnicode_Count(PyObject *str,
9363 PyObject *substr,
9364 Py_ssize_t start,
9365 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009367 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009368 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009369 void *buf1 = NULL, *buf2 = NULL;
9370 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009371
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009372 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009373 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009374
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009375 kind1 = PyUnicode_KIND(str);
9376 kind2 = PyUnicode_KIND(substr);
9377 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009378 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009379
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009380 len1 = PyUnicode_GET_LENGTH(str);
9381 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009383 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009384 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009385
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009386 buf1 = PyUnicode_DATA(str);
9387 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009388 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009389 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009390 if (!buf2)
9391 goto onError;
9392 }
9393
9394 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009396 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009397 result = asciilib_count(
9398 ((Py_UCS1*)buf1) + start, end - start,
9399 buf2, len2, PY_SSIZE_T_MAX
9400 );
9401 else
9402 result = ucs1lib_count(
9403 ((Py_UCS1*)buf1) + start, end - start,
9404 buf2, len2, PY_SSIZE_T_MAX
9405 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406 break;
9407 case PyUnicode_2BYTE_KIND:
9408 result = ucs2lib_count(
9409 ((Py_UCS2*)buf1) + start, end - start,
9410 buf2, len2, PY_SSIZE_T_MAX
9411 );
9412 break;
9413 case PyUnicode_4BYTE_KIND:
9414 result = ucs4lib_count(
9415 ((Py_UCS4*)buf1) + start, end - start,
9416 buf2, len2, PY_SSIZE_T_MAX
9417 );
9418 break;
9419 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009420 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009422
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009423 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009424 PyMem_Free(buf2);
9425
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009428 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 PyMem_Free(buf2);
9430 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009431}
9432
Alexander Belopolsky40018472011-02-26 01:02:56 +00009433Py_ssize_t
9434PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009435 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009436 Py_ssize_t start,
9437 Py_ssize_t end,
9438 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009439{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009440 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009441 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009442
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009443 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009444}
9445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446Py_ssize_t
9447PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9448 Py_ssize_t start, Py_ssize_t end,
9449 int direction)
9450{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009452 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453 if (PyUnicode_READY(str) == -1)
9454 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009455 len = PyUnicode_GET_LENGTH(str);
9456 ADJUST_INDICES(start, end, len);
9457 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009458 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009460 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9461 kind, end-start, ch, direction);
9462 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009464 else
9465 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466}
9467
Alexander Belopolsky40018472011-02-26 01:02:56 +00009468static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009469tailmatch(PyObject *self,
9470 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009471 Py_ssize_t start,
9472 Py_ssize_t end,
9473 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 int kind_self;
9476 int kind_sub;
9477 void *data_self;
9478 void *data_sub;
9479 Py_ssize_t offset;
9480 Py_ssize_t i;
9481 Py_ssize_t end_sub;
9482
9483 if (PyUnicode_READY(self) == -1 ||
9484 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009485 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9488 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009490 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009492 if (PyUnicode_GET_LENGTH(substring) == 0)
9493 return 1;
9494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 kind_self = PyUnicode_KIND(self);
9496 data_self = PyUnicode_DATA(self);
9497 kind_sub = PyUnicode_KIND(substring);
9498 data_sub = PyUnicode_DATA(substring);
9499 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9500
9501 if (direction > 0)
9502 offset = end;
9503 else
9504 offset = start;
9505
9506 if (PyUnicode_READ(kind_self, data_self, offset) ==
9507 PyUnicode_READ(kind_sub, data_sub, 0) &&
9508 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9509 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9510 /* If both are of the same kind, memcmp is sufficient */
9511 if (kind_self == kind_sub) {
9512 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009513 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 data_sub,
9515 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009516 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009517 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009518 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 else {
9520 /* We do not need to compare 0 and len(substring)-1 because
9521 the if statement above ensured already that they are equal
9522 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523 for (i = 1; i < end_sub; ++i) {
9524 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9525 PyUnicode_READ(kind_sub, data_sub, i))
9526 return 0;
9527 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009528 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530 }
9531
9532 return 0;
9533}
9534
Alexander Belopolsky40018472011-02-26 01:02:56 +00009535Py_ssize_t
9536PyUnicode_Tailmatch(PyObject *str,
9537 PyObject *substr,
9538 Py_ssize_t start,
9539 Py_ssize_t end,
9540 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009541{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009542 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009543 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009544
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009545 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546}
9547
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009548static PyObject *
9549ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009550{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009551 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9552 char *resdata, *data = PyUnicode_DATA(self);
9553 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009554
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009555 res = PyUnicode_New(len, 127);
9556 if (res == NULL)
9557 return NULL;
9558 resdata = PyUnicode_DATA(res);
9559 if (lower)
9560 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009562 _Py_bytes_upper(resdata, data, len);
9563 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564}
9565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009567handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009568{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009569 Py_ssize_t j;
9570 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009571 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009572 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009573
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009574 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9575
9576 where ! is a negation and \p{xxx} is a character with property xxx.
9577 */
9578 for (j = i - 1; j >= 0; j--) {
9579 c = PyUnicode_READ(kind, data, j);
9580 if (!_PyUnicode_IsCaseIgnorable(c))
9581 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009582 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009583 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9584 if (final_sigma) {
9585 for (j = i + 1; j < length; j++) {
9586 c = PyUnicode_READ(kind, data, j);
9587 if (!_PyUnicode_IsCaseIgnorable(c))
9588 break;
9589 }
9590 final_sigma = j == length || !_PyUnicode_IsCased(c);
9591 }
9592 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593}
9594
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009595static int
9596lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9597 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009598{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009599 /* Obscure special case. */
9600 if (c == 0x3A3) {
9601 mapped[0] = handle_capital_sigma(kind, data, length, i);
9602 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009603 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009604 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009605}
9606
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009607static Py_ssize_t
9608do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009609{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009610 Py_ssize_t i, k = 0;
9611 int n_res, j;
9612 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009613
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009614 c = PyUnicode_READ(kind, data, 0);
9615 n_res = _PyUnicode_ToUpperFull(c, mapped);
9616 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009617 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009618 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009619 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009620 for (i = 1; i < length; i++) {
9621 c = PyUnicode_READ(kind, data, i);
9622 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9623 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009624 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009625 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009626 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009627 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009628 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009629}
9630
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009631static Py_ssize_t
9632do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9633 Py_ssize_t i, k = 0;
9634
9635 for (i = 0; i < length; i++) {
9636 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9637 int n_res, j;
9638 if (Py_UNICODE_ISUPPER(c)) {
9639 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9640 }
9641 else if (Py_UNICODE_ISLOWER(c)) {
9642 n_res = _PyUnicode_ToUpperFull(c, mapped);
9643 }
9644 else {
9645 n_res = 1;
9646 mapped[0] = c;
9647 }
9648 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009649 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009650 res[k++] = mapped[j];
9651 }
9652 }
9653 return k;
9654}
9655
9656static Py_ssize_t
9657do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9658 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009659{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009660 Py_ssize_t i, k = 0;
9661
9662 for (i = 0; i < length; i++) {
9663 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9664 int n_res, j;
9665 if (lower)
9666 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9667 else
9668 n_res = _PyUnicode_ToUpperFull(c, mapped);
9669 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009670 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009671 res[k++] = mapped[j];
9672 }
9673 }
9674 return k;
9675}
9676
9677static Py_ssize_t
9678do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9679{
9680 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9681}
9682
9683static Py_ssize_t
9684do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9685{
9686 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9687}
9688
Benjamin Petersone51757f2012-01-12 21:10:29 -05009689static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009690do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9691{
9692 Py_ssize_t i, k = 0;
9693
9694 for (i = 0; i < length; i++) {
9695 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9696 Py_UCS4 mapped[3];
9697 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9698 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009699 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009700 res[k++] = mapped[j];
9701 }
9702 }
9703 return k;
9704}
9705
9706static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009707do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9708{
9709 Py_ssize_t i, k = 0;
9710 int previous_is_cased;
9711
9712 previous_is_cased = 0;
9713 for (i = 0; i < length; i++) {
9714 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9715 Py_UCS4 mapped[3];
9716 int n_res, j;
9717
9718 if (previous_is_cased)
9719 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9720 else
9721 n_res = _PyUnicode_ToTitleFull(c, mapped);
9722
9723 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009724 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009725 res[k++] = mapped[j];
9726 }
9727
9728 previous_is_cased = _PyUnicode_IsCased(c);
9729 }
9730 return k;
9731}
9732
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009733static PyObject *
9734case_operation(PyObject *self,
9735 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9736{
9737 PyObject *res = NULL;
9738 Py_ssize_t length, newlength = 0;
9739 int kind, outkind;
9740 void *data, *outdata;
9741 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9742
Benjamin Petersoneea48462012-01-16 14:28:50 -05009743 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009744
9745 kind = PyUnicode_KIND(self);
9746 data = PyUnicode_DATA(self);
9747 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009748 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009749 PyErr_SetString(PyExc_OverflowError, "string is too long");
9750 return NULL;
9751 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009752 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009753 if (tmp == NULL)
9754 return PyErr_NoMemory();
9755 newlength = perform(kind, data, length, tmp, &maxchar);
9756 res = PyUnicode_New(newlength, maxchar);
9757 if (res == NULL)
9758 goto leave;
9759 tmpend = tmp + newlength;
9760 outdata = PyUnicode_DATA(res);
9761 outkind = PyUnicode_KIND(res);
9762 switch (outkind) {
9763 case PyUnicode_1BYTE_KIND:
9764 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9765 break;
9766 case PyUnicode_2BYTE_KIND:
9767 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9768 break;
9769 case PyUnicode_4BYTE_KIND:
9770 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9771 break;
9772 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009773 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009774 }
9775 leave:
9776 PyMem_FREE(tmp);
9777 return res;
9778}
9779
Tim Peters8ce9f162004-08-27 01:49:32 +00009780PyObject *
9781PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009783 PyObject *res;
9784 PyObject *fseq;
9785 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009786 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009787
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009788 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009789 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009790 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009791 }
9792
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009793 /* NOTE: the following code can't call back into Python code,
9794 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009795 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009796
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009797 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009798 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009799 res = _PyUnicode_JoinArray(separator, items, seqlen);
9800 Py_DECREF(fseq);
9801 return res;
9802}
9803
9804PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009805_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009806{
9807 PyObject *res = NULL; /* the result */
9808 PyObject *sep = NULL;
9809 Py_ssize_t seplen;
9810 PyObject *item;
9811 Py_ssize_t sz, i, res_offset;
9812 Py_UCS4 maxchar;
9813 Py_UCS4 item_maxchar;
9814 int use_memcpy;
9815 unsigned char *res_data = NULL, *sep_data = NULL;
9816 PyObject *last_obj;
9817 unsigned int kind = 0;
9818
Tim Peters05eba1f2004-08-27 21:32:02 +00009819 /* If empty sequence, return u"". */
9820 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009821 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009822 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009823
Tim Peters05eba1f2004-08-27 21:32:02 +00009824 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009825 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009826 if (seqlen == 1) {
9827 if (PyUnicode_CheckExact(items[0])) {
9828 res = items[0];
9829 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009830 return res;
9831 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009832 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009833 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009834 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009835 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009836 /* Set up sep and seplen */
9837 if (separator == NULL) {
9838 /* fall back to a blank space separator */
9839 sep = PyUnicode_FromOrdinal(' ');
9840 if (!sep)
9841 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009842 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009843 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009844 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009845 else {
9846 if (!PyUnicode_Check(separator)) {
9847 PyErr_Format(PyExc_TypeError,
9848 "separator: expected str instance,"
9849 " %.80s found",
9850 Py_TYPE(separator)->tp_name);
9851 goto onError;
9852 }
9853 if (PyUnicode_READY(separator))
9854 goto onError;
9855 sep = separator;
9856 seplen = PyUnicode_GET_LENGTH(separator);
9857 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9858 /* inc refcount to keep this code path symmetric with the
9859 above case of a blank separator */
9860 Py_INCREF(sep);
9861 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009862 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009863 }
9864
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009865 /* There are at least two things to join, or else we have a subclass
9866 * of str in the sequence.
9867 * Do a pre-pass to figure out the total amount of space we'll
9868 * need (sz), and see whether all argument are strings.
9869 */
9870 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009871#ifdef Py_DEBUG
9872 use_memcpy = 0;
9873#else
9874 use_memcpy = 1;
9875#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009876 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009877 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009878 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009879 if (!PyUnicode_Check(item)) {
9880 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009881 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009882 " %.80s found",
9883 i, Py_TYPE(item)->tp_name);
9884 goto onError;
9885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 if (PyUnicode_READY(item) == -1)
9887 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009888 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009890 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009891 if (i != 0) {
9892 add_sz += seplen;
9893 }
9894 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009895 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009896 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009897 goto onError;
9898 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009899 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009900 if (use_memcpy && last_obj != NULL) {
9901 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9902 use_memcpy = 0;
9903 }
9904 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009905 }
Tim Petersced69f82003-09-16 20:30:58 +00009906
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009907 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009908 if (res == NULL)
9909 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009910
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009911 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009912#ifdef Py_DEBUG
9913 use_memcpy = 0;
9914#else
9915 if (use_memcpy) {
9916 res_data = PyUnicode_1BYTE_DATA(res);
9917 kind = PyUnicode_KIND(res);
9918 if (seplen != 0)
9919 sep_data = PyUnicode_1BYTE_DATA(sep);
9920 }
9921#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009922 if (use_memcpy) {
9923 for (i = 0; i < seqlen; ++i) {
9924 Py_ssize_t itemlen;
9925 item = items[i];
9926
9927 /* Copy item, and maybe the separator. */
9928 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009929 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009930 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009931 kind * seplen);
9932 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009933 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009934
9935 itemlen = PyUnicode_GET_LENGTH(item);
9936 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009937 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009938 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009939 kind * itemlen);
9940 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009941 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009942 }
9943 assert(res_data == PyUnicode_1BYTE_DATA(res)
9944 + kind * PyUnicode_GET_LENGTH(res));
9945 }
9946 else {
9947 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9948 Py_ssize_t itemlen;
9949 item = items[i];
9950
9951 /* Copy item, and maybe the separator. */
9952 if (i && seplen != 0) {
9953 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9954 res_offset += seplen;
9955 }
9956
9957 itemlen = PyUnicode_GET_LENGTH(item);
9958 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009959 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009960 res_offset += itemlen;
9961 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009962 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009963 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009964 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009967 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009969
Benjamin Peterson29060642009-01-31 22:14:21 +00009970 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009972 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009973 return NULL;
9974}
9975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976#define FILL(kind, data, value, start, length) \
9977 do { \
9978 Py_ssize_t i_ = 0; \
9979 assert(kind != PyUnicode_WCHAR_KIND); \
9980 switch ((kind)) { \
9981 case PyUnicode_1BYTE_KIND: { \
9982 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009983 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 break; \
9985 } \
9986 case PyUnicode_2BYTE_KIND: { \
9987 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9988 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9989 break; \
9990 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009991 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009992 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9993 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9994 break; \
9995 } \
Barry Warsawb2e57942017-09-14 18:13:16 -07009996 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997 } \
9998 } while (0)
9999
Victor Stinnerd3f08822012-05-29 12:57:52 +020010000void
10001_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10002 Py_UCS4 fill_char)
10003{
10004 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10005 const void *data = PyUnicode_DATA(unicode);
10006 assert(PyUnicode_IS_READY(unicode));
10007 assert(unicode_modifiable(unicode));
10008 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10009 assert(start >= 0);
10010 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10011 FILL(kind, data, fill_char, start, length);
10012}
10013
Victor Stinner3fe55312012-01-04 00:33:50 +010010014Py_ssize_t
10015PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10016 Py_UCS4 fill_char)
10017{
10018 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010019
10020 if (!PyUnicode_Check(unicode)) {
10021 PyErr_BadInternalCall();
10022 return -1;
10023 }
10024 if (PyUnicode_READY(unicode) == -1)
10025 return -1;
10026 if (unicode_check_modifiable(unicode))
10027 return -1;
10028
Victor Stinnerd3f08822012-05-29 12:57:52 +020010029 if (start < 0) {
10030 PyErr_SetString(PyExc_IndexError, "string index out of range");
10031 return -1;
10032 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010033 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10034 PyErr_SetString(PyExc_ValueError,
10035 "fill character is bigger than "
10036 "the string maximum character");
10037 return -1;
10038 }
10039
10040 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10041 length = Py_MIN(maxlen, length);
10042 if (length <= 0)
10043 return 0;
10044
Victor Stinnerd3f08822012-05-29 12:57:52 +020010045 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010046 return length;
10047}
10048
Victor Stinner9310abb2011-10-05 00:59:23 +020010049static PyObject *
10050pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010051 Py_ssize_t left,
10052 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010054{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 PyObject *u;
10056 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010057 int kind;
10058 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010059
10060 if (left < 0)
10061 left = 0;
10062 if (right < 0)
10063 right = 0;
10064
Victor Stinnerc4b49542011-12-11 22:44:26 +010010065 if (left == 0 && right == 0)
10066 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10069 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010070 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10071 return NULL;
10072 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010074 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010075 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010076 if (!u)
10077 return NULL;
10078
10079 kind = PyUnicode_KIND(u);
10080 data = PyUnicode_DATA(u);
10081 if (left)
10082 FILL(kind, data, fill, 0, left);
10083 if (right)
10084 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010085 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010086 assert(_PyUnicode_CheckConsistency(u, 1));
10087 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010088}
10089
Alexander Belopolsky40018472011-02-26 01:02:56 +000010090PyObject *
10091PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010093 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010094
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010095 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010096 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010097
Benjamin Petersonead6b532011-12-20 17:23:42 -060010098 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010099 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010100 if (PyUnicode_IS_ASCII(string))
10101 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010102 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010103 PyUnicode_GET_LENGTH(string), keepends);
10104 else
10105 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010106 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010107 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 break;
10109 case PyUnicode_2BYTE_KIND:
10110 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010111 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 PyUnicode_GET_LENGTH(string), keepends);
10113 break;
10114 case PyUnicode_4BYTE_KIND:
10115 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010116 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 PyUnicode_GET_LENGTH(string), keepends);
10118 break;
10119 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010120 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010122 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010123}
10124
Alexander Belopolsky40018472011-02-26 01:02:56 +000010125static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010126split(PyObject *self,
10127 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010128 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010129{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010130 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 void *buf1, *buf2;
10132 Py_ssize_t len1, len2;
10133 PyObject* out;
10134
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010136 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 if (PyUnicode_READY(self) == -1)
10139 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010142 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010144 if (PyUnicode_IS_ASCII(self))
10145 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010146 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010147 PyUnicode_GET_LENGTH(self), maxcount
10148 );
10149 else
10150 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010151 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010152 PyUnicode_GET_LENGTH(self), maxcount
10153 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 case PyUnicode_2BYTE_KIND:
10155 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010156 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 PyUnicode_GET_LENGTH(self), maxcount
10158 );
10159 case PyUnicode_4BYTE_KIND:
10160 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010161 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 PyUnicode_GET_LENGTH(self), maxcount
10163 );
10164 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010165 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 }
10167
10168 if (PyUnicode_READY(substring) == -1)
10169 return NULL;
10170
10171 kind1 = PyUnicode_KIND(self);
10172 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 len1 = PyUnicode_GET_LENGTH(self);
10174 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010175 if (kind1 < kind2 || len1 < len2) {
10176 out = PyList_New(1);
10177 if (out == NULL)
10178 return NULL;
10179 Py_INCREF(self);
10180 PyList_SET_ITEM(out, 0, self);
10181 return out;
10182 }
10183 buf1 = PyUnicode_DATA(self);
10184 buf2 = PyUnicode_DATA(substring);
10185 if (kind2 != kind1) {
10186 buf2 = _PyUnicode_AsKind(substring, kind1);
10187 if (!buf2)
10188 return NULL;
10189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010191 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010193 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10194 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010195 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010196 else
10197 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010198 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 break;
10200 case PyUnicode_2BYTE_KIND:
10201 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 break;
10204 case PyUnicode_4BYTE_KIND:
10205 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010206 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 break;
10208 default:
10209 out = NULL;
10210 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010211 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 PyMem_Free(buf2);
10213 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214}
10215
Alexander Belopolsky40018472011-02-26 01:02:56 +000010216static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010217rsplit(PyObject *self,
10218 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010219 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010220{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010221 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 void *buf1, *buf2;
10223 Py_ssize_t len1, len2;
10224 PyObject* out;
10225
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010226 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010227 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 if (PyUnicode_READY(self) == -1)
10230 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010233 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010235 if (PyUnicode_IS_ASCII(self))
10236 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010237 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010238 PyUnicode_GET_LENGTH(self), maxcount
10239 );
10240 else
10241 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010242 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010243 PyUnicode_GET_LENGTH(self), maxcount
10244 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 case PyUnicode_2BYTE_KIND:
10246 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010247 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 PyUnicode_GET_LENGTH(self), maxcount
10249 );
10250 case PyUnicode_4BYTE_KIND:
10251 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010252 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 PyUnicode_GET_LENGTH(self), maxcount
10254 );
10255 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010256 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 }
10258
10259 if (PyUnicode_READY(substring) == -1)
10260 return NULL;
10261
10262 kind1 = PyUnicode_KIND(self);
10263 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 len1 = PyUnicode_GET_LENGTH(self);
10265 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010266 if (kind1 < kind2 || len1 < len2) {
10267 out = PyList_New(1);
10268 if (out == NULL)
10269 return NULL;
10270 Py_INCREF(self);
10271 PyList_SET_ITEM(out, 0, self);
10272 return out;
10273 }
10274 buf1 = PyUnicode_DATA(self);
10275 buf2 = PyUnicode_DATA(substring);
10276 if (kind2 != kind1) {
10277 buf2 = _PyUnicode_AsKind(substring, kind1);
10278 if (!buf2)
10279 return NULL;
10280 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010282 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010284 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10285 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010286 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010287 else
10288 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010289 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 break;
10291 case PyUnicode_2BYTE_KIND:
10292 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010293 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 break;
10295 case PyUnicode_4BYTE_KIND:
10296 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010297 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 break;
10299 default:
10300 out = NULL;
10301 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010302 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 PyMem_Free(buf2);
10304 return out;
10305}
10306
10307static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010308anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10309 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010311 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010313 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10314 return asciilib_find(buf1, len1, buf2, len2, offset);
10315 else
10316 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 case PyUnicode_2BYTE_KIND:
10318 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10319 case PyUnicode_4BYTE_KIND:
10320 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10321 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010322 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323}
10324
10325static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010326anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10327 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010329 switch (kind) {
10330 case PyUnicode_1BYTE_KIND:
10331 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10332 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10333 else
10334 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10335 case PyUnicode_2BYTE_KIND:
10336 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10337 case PyUnicode_4BYTE_KIND:
10338 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10339 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010340 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010341}
10342
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010343static void
10344replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10345 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10346{
10347 int kind = PyUnicode_KIND(u);
10348 void *data = PyUnicode_DATA(u);
10349 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10350 if (kind == PyUnicode_1BYTE_KIND) {
10351 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10352 (Py_UCS1 *)data + len,
10353 u1, u2, maxcount);
10354 }
10355 else if (kind == PyUnicode_2BYTE_KIND) {
10356 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10357 (Py_UCS2 *)data + len,
10358 u1, u2, maxcount);
10359 }
10360 else {
10361 assert(kind == PyUnicode_4BYTE_KIND);
10362 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10363 (Py_UCS4 *)data + len,
10364 u1, u2, maxcount);
10365 }
10366}
10367
Alexander Belopolsky40018472011-02-26 01:02:56 +000010368static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369replace(PyObject *self, PyObject *str1,
10370 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010371{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 PyObject *u;
10373 char *sbuf = PyUnicode_DATA(self);
10374 char *buf1 = PyUnicode_DATA(str1);
10375 char *buf2 = PyUnicode_DATA(str2);
10376 int srelease = 0, release1 = 0, release2 = 0;
10377 int skind = PyUnicode_KIND(self);
10378 int kind1 = PyUnicode_KIND(str1);
10379 int kind2 = PyUnicode_KIND(str2);
10380 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10381 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10382 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010383 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010384 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385
10386 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010387 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010389 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010390
Victor Stinner59de0ee2011-10-07 10:01:28 +020010391 if (str1 == str2)
10392 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393
Victor Stinner49a0a212011-10-12 23:46:10 +020010394 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010395 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10396 if (maxchar < maxchar_str1)
10397 /* substring too wide to be present */
10398 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010399 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10400 /* Replacing str1 with str2 may cause a maxchar reduction in the
10401 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010402 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010403 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010406 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010408 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010410 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010411 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010412 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010413
Victor Stinner69ed0f42013-04-09 21:48:24 +020010414 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010415 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010416 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010417 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010418 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010420 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010422
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010423 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10424 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010425 }
10426 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 int rkind = skind;
10428 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010429 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 if (kind1 < rkind) {
10432 /* widen substring */
10433 buf1 = _PyUnicode_AsKind(str1, rkind);
10434 if (!buf1) goto error;
10435 release1 = 1;
10436 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010437 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010438 if (i < 0)
10439 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 if (rkind > kind2) {
10441 /* widen replacement */
10442 buf2 = _PyUnicode_AsKind(str2, rkind);
10443 if (!buf2) goto error;
10444 release2 = 1;
10445 }
10446 else if (rkind < kind2) {
10447 /* widen self and buf1 */
10448 rkind = kind2;
10449 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010450 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 sbuf = _PyUnicode_AsKind(self, rkind);
10452 if (!sbuf) goto error;
10453 srelease = 1;
10454 buf1 = _PyUnicode_AsKind(str1, rkind);
10455 if (!buf1) goto error;
10456 release1 = 1;
10457 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010458 u = PyUnicode_New(slen, maxchar);
10459 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010461 assert(PyUnicode_KIND(u) == rkind);
10462 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010463
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010464 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010465 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010466 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010468 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010470
10471 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010472 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010473 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010474 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010475 if (i == -1)
10476 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010477 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010479 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010480 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010481 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010482 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010483 }
10484 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010486 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 int rkind = skind;
10488 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010489
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010491 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 buf1 = _PyUnicode_AsKind(str1, rkind);
10493 if (!buf1) goto error;
10494 release1 = 1;
10495 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010496 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010497 if (n == 0)
10498 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010500 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 buf2 = _PyUnicode_AsKind(str2, rkind);
10502 if (!buf2) goto error;
10503 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010506 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010507 rkind = kind2;
10508 sbuf = _PyUnicode_AsKind(self, rkind);
10509 if (!sbuf) goto error;
10510 srelease = 1;
10511 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010512 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 buf1 = _PyUnicode_AsKind(str1, rkind);
10514 if (!buf1) goto error;
10515 release1 = 1;
10516 }
10517 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10518 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010519 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 PyErr_SetString(PyExc_OverflowError,
10521 "replace string is too long");
10522 goto error;
10523 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010524 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010525 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010526 _Py_INCREF_UNICODE_EMPTY();
10527 if (!unicode_empty)
10528 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010529 u = unicode_empty;
10530 goto done;
10531 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010532 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 PyErr_SetString(PyExc_OverflowError,
10534 "replace string is too long");
10535 goto error;
10536 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010537 u = PyUnicode_New(new_size, maxchar);
10538 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010539 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010540 assert(PyUnicode_KIND(u) == rkind);
10541 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010542 ires = i = 0;
10543 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010544 while (n-- > 0) {
10545 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010546 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010547 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010548 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010549 if (j == -1)
10550 break;
10551 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010552 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010553 memcpy(res + rkind * ires,
10554 sbuf + rkind * i,
10555 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010557 }
10558 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010560 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010562 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010564 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010566 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010568 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010569 memcpy(res + rkind * ires,
10570 sbuf + rkind * i,
10571 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010572 }
10573 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010574 /* interleave */
10575 while (n > 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 if (--n <= 0)
10581 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010582 memcpy(res + rkind * ires,
10583 sbuf + rkind * i,
10584 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 ires++;
10586 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010588 memcpy(res + rkind * ires,
10589 sbuf + rkind * i,
10590 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010591 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010592 }
10593
10594 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010595 unicode_adjust_maxchar(&u);
10596 if (u == NULL)
10597 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010598 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010599
10600 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 if (srelease)
10602 PyMem_FREE(sbuf);
10603 if (release1)
10604 PyMem_FREE(buf1);
10605 if (release2)
10606 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010607 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010609
Benjamin Peterson29060642009-01-31 22:14:21 +000010610 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010611 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 if (srelease)
10613 PyMem_FREE(sbuf);
10614 if (release1)
10615 PyMem_FREE(buf1);
10616 if (release2)
10617 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010618 return unicode_result_unchanged(self);
10619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620 error:
10621 if (srelease && sbuf)
10622 PyMem_FREE(sbuf);
10623 if (release1 && buf1)
10624 PyMem_FREE(buf1);
10625 if (release2 && buf2)
10626 PyMem_FREE(buf2);
10627 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628}
10629
10630/* --- Unicode Object Methods --------------------------------------------- */
10631
INADA Naoki3ae20562017-01-16 20:41:20 +090010632/*[clinic input]
10633str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634
INADA Naoki3ae20562017-01-16 20:41:20 +090010635Return a version of the string where each word is titlecased.
10636
10637More specifically, words start with uppercased characters and all remaining
10638cased characters have lower case.
10639[clinic start generated code]*/
10640
10641static PyObject *
10642unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010643/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010645 if (PyUnicode_READY(self) == -1)
10646 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010647 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010648}
10649
INADA Naoki3ae20562017-01-16 20:41:20 +090010650/*[clinic input]
10651str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010652
INADA Naoki3ae20562017-01-16 20:41:20 +090010653Return a capitalized version of the string.
10654
10655More specifically, make the first character have upper case and the rest lower
10656case.
10657[clinic start generated code]*/
10658
10659static PyObject *
10660unicode_capitalize_impl(PyObject *self)
10661/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010663 if (PyUnicode_READY(self) == -1)
10664 return NULL;
10665 if (PyUnicode_GET_LENGTH(self) == 0)
10666 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010667 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010668}
10669
INADA Naoki3ae20562017-01-16 20:41:20 +090010670/*[clinic input]
10671str.casefold as unicode_casefold
10672
10673Return a version of the string suitable for caseless comparisons.
10674[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010675
10676static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010677unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010678/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010679{
10680 if (PyUnicode_READY(self) == -1)
10681 return NULL;
10682 if (PyUnicode_IS_ASCII(self))
10683 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010684 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010685}
10686
10687
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010688/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010689
10690static int
10691convert_uc(PyObject *obj, void *addr)
10692{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010694
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010695 if (!PyUnicode_Check(obj)) {
10696 PyErr_Format(PyExc_TypeError,
10697 "The fill character must be a unicode character, "
10698 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010699 return 0;
10700 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010701 if (PyUnicode_READY(obj) < 0)
10702 return 0;
10703 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010704 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010705 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010706 return 0;
10707 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010708 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010709 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010710}
10711
INADA Naoki3ae20562017-01-16 20:41:20 +090010712/*[clinic input]
10713str.center as unicode_center
10714
10715 width: Py_ssize_t
10716 fillchar: Py_UCS4 = ' '
10717 /
10718
10719Return a centered string of length width.
10720
10721Padding is done using the specified fill character (default is a space).
10722[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723
10724static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010725unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10726/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010727{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010728 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010729
Benjamin Petersonbac79492012-01-14 13:34:47 -050010730 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010731 return NULL;
10732
Victor Stinnerc4b49542011-12-11 22:44:26 +010010733 if (PyUnicode_GET_LENGTH(self) >= width)
10734 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010735
Victor Stinnerc4b49542011-12-11 22:44:26 +010010736 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010737 left = marg / 2 + (marg & width & 1);
10738
Victor Stinner9310abb2011-10-05 00:59:23 +020010739 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010740}
10741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742/* This function assumes that str1 and str2 are readied by the caller. */
10743
Marc-André Lemburge5034372000-08-08 08:04:29 +000010744static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010745unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010746{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010747#define COMPARE(TYPE1, TYPE2) \
10748 do { \
10749 TYPE1* p1 = (TYPE1 *)data1; \
10750 TYPE2* p2 = (TYPE2 *)data2; \
10751 TYPE1* end = p1 + len; \
10752 Py_UCS4 c1, c2; \
10753 for (; p1 != end; p1++, p2++) { \
10754 c1 = *p1; \
10755 c2 = *p2; \
10756 if (c1 != c2) \
10757 return (c1 < c2) ? -1 : 1; \
10758 } \
10759 } \
10760 while (0)
10761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010762 int kind1, kind2;
10763 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010764 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 kind1 = PyUnicode_KIND(str1);
10767 kind2 = PyUnicode_KIND(str2);
10768 data1 = PyUnicode_DATA(str1);
10769 data2 = PyUnicode_DATA(str2);
10770 len1 = PyUnicode_GET_LENGTH(str1);
10771 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010772 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010773
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010774 switch(kind1) {
10775 case PyUnicode_1BYTE_KIND:
10776 {
10777 switch(kind2) {
10778 case PyUnicode_1BYTE_KIND:
10779 {
10780 int cmp = memcmp(data1, data2, len);
10781 /* normalize result of memcmp() into the range [-1; 1] */
10782 if (cmp < 0)
10783 return -1;
10784 if (cmp > 0)
10785 return 1;
10786 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010787 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010788 case PyUnicode_2BYTE_KIND:
10789 COMPARE(Py_UCS1, Py_UCS2);
10790 break;
10791 case PyUnicode_4BYTE_KIND:
10792 COMPARE(Py_UCS1, Py_UCS4);
10793 break;
10794 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010795 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010796 }
10797 break;
10798 }
10799 case PyUnicode_2BYTE_KIND:
10800 {
10801 switch(kind2) {
10802 case PyUnicode_1BYTE_KIND:
10803 COMPARE(Py_UCS2, Py_UCS1);
10804 break;
10805 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010806 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010807 COMPARE(Py_UCS2, Py_UCS2);
10808 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010809 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010810 case PyUnicode_4BYTE_KIND:
10811 COMPARE(Py_UCS2, Py_UCS4);
10812 break;
10813 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010814 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010815 }
10816 break;
10817 }
10818 case PyUnicode_4BYTE_KIND:
10819 {
10820 switch(kind2) {
10821 case PyUnicode_1BYTE_KIND:
10822 COMPARE(Py_UCS4, Py_UCS1);
10823 break;
10824 case PyUnicode_2BYTE_KIND:
10825 COMPARE(Py_UCS4, Py_UCS2);
10826 break;
10827 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010828 {
10829#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10830 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10831 /* normalize result of wmemcmp() into the range [-1; 1] */
10832 if (cmp < 0)
10833 return -1;
10834 if (cmp > 0)
10835 return 1;
10836#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010837 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010838#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010839 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010840 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010841 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010842 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010843 }
10844 break;
10845 }
10846 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010847 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010848 }
10849
Victor Stinner770e19e2012-10-04 22:59:45 +020010850 if (len1 == len2)
10851 return 0;
10852 if (len1 < len2)
10853 return -1;
10854 else
10855 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010856
10857#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010858}
10859
Benjamin Peterson621b4302016-09-09 13:54:34 -070010860static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010861unicode_compare_eq(PyObject *str1, PyObject *str2)
10862{
10863 int kind;
10864 void *data1, *data2;
10865 Py_ssize_t len;
10866 int cmp;
10867
Victor Stinnere5567ad2012-10-23 02:48:49 +020010868 len = PyUnicode_GET_LENGTH(str1);
10869 if (PyUnicode_GET_LENGTH(str2) != len)
10870 return 0;
10871 kind = PyUnicode_KIND(str1);
10872 if (PyUnicode_KIND(str2) != kind)
10873 return 0;
10874 data1 = PyUnicode_DATA(str1);
10875 data2 = PyUnicode_DATA(str2);
10876
10877 cmp = memcmp(data1, data2, len * kind);
10878 return (cmp == 0);
10879}
10880
10881
Alexander Belopolsky40018472011-02-26 01:02:56 +000010882int
10883PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010885 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10886 if (PyUnicode_READY(left) == -1 ||
10887 PyUnicode_READY(right) == -1)
10888 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010889
10890 /* a string is equal to itself */
10891 if (left == right)
10892 return 0;
10893
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010894 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010896 PyErr_Format(PyExc_TypeError,
10897 "Can't compare %.100s and %.100s",
10898 left->ob_type->tp_name,
10899 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010900 return -1;
10901}
10902
Martin v. Löwis5b222132007-06-10 09:51:05 +000010903int
10904PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10905{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010906 Py_ssize_t i;
10907 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010908 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010909 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010910
Victor Stinner910337b2011-10-03 03:20:16 +020010911 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010912 if (!PyUnicode_IS_READY(uni)) {
10913 const wchar_t *ws = _PyUnicode_WSTR(uni);
10914 /* Compare Unicode string and source character set string */
10915 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10916 if (chr != ustr[i])
10917 return (chr < ustr[i]) ? -1 : 1;
10918 }
10919 /* This check keeps Python strings that end in '\0' from comparing equal
10920 to C strings identical up to that point. */
10921 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10922 return 1; /* uni is longer */
10923 if (ustr[i])
10924 return -1; /* str is longer */
10925 return 0;
10926 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010928 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010929 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010930 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010931 size_t len, len2 = strlen(str);
10932 int cmp;
10933
10934 len = Py_MIN(len1, len2);
10935 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010936 if (cmp != 0) {
10937 if (cmp < 0)
10938 return -1;
10939 else
10940 return 1;
10941 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010942 if (len1 > len2)
10943 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010944 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010945 return -1; /* str is longer */
10946 return 0;
10947 }
10948 else {
10949 void *data = PyUnicode_DATA(uni);
10950 /* Compare Unicode string and source character set string */
10951 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010952 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010953 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10954 /* This check keeps Python strings that end in '\0' from comparing equal
10955 to C strings identical up to that point. */
10956 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10957 return 1; /* uni is longer */
10958 if (str[i])
10959 return -1; /* str is longer */
10960 return 0;
10961 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010962}
10963
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010964static int
10965non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
10966{
10967 size_t i, len;
10968 const wchar_t *p;
10969 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
10970 if (strlen(str) != len)
10971 return 0;
10972 p = _PyUnicode_WSTR(unicode);
10973 assert(p);
10974 for (i = 0; i < len; i++) {
10975 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020010976 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010977 return 0;
10978 }
10979 return 1;
10980}
10981
10982int
10983_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
10984{
10985 size_t len;
10986 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020010987 assert(str);
10988#ifndef NDEBUG
10989 for (const char *p = str; *p; p++) {
10990 assert((unsigned char)*p < 128);
10991 }
10992#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010993 if (PyUnicode_READY(unicode) == -1) {
10994 /* Memory error or bad data */
10995 PyErr_Clear();
10996 return non_ready_unicode_equal_to_ascii_string(unicode, str);
10997 }
10998 if (!PyUnicode_IS_ASCII(unicode))
10999 return 0;
11000 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11001 return strlen(str) == len &&
11002 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11003}
11004
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011005int
11006_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11007{
11008 PyObject *right_uni;
11009 Py_hash_t hash;
11010
11011 assert(_PyUnicode_CHECK(left));
11012 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011013#ifndef NDEBUG
11014 for (const char *p = right->string; *p; p++) {
11015 assert((unsigned char)*p < 128);
11016 }
11017#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011018
11019 if (PyUnicode_READY(left) == -1) {
11020 /* memory error or bad data */
11021 PyErr_Clear();
11022 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11023 }
11024
11025 if (!PyUnicode_IS_ASCII(left))
11026 return 0;
11027
11028 right_uni = _PyUnicode_FromId(right); /* borrowed */
11029 if (right_uni == NULL) {
11030 /* memory error or bad data */
11031 PyErr_Clear();
11032 return _PyUnicode_EqualToASCIIString(left, right->string);
11033 }
11034
11035 if (left == right_uni)
11036 return 1;
11037
11038 if (PyUnicode_CHECK_INTERNED(left))
11039 return 0;
11040
11041 assert(_PyUnicode_HASH(right_uni) != 1);
11042 hash = _PyUnicode_HASH(left);
11043 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11044 return 0;
11045
11046 return unicode_compare_eq(left, right_uni);
11047}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011048
Alexander Belopolsky40018472011-02-26 01:02:56 +000011049PyObject *
11050PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011051{
11052 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011053
Victor Stinnere5567ad2012-10-23 02:48:49 +020011054 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11055 Py_RETURN_NOTIMPLEMENTED;
11056
11057 if (PyUnicode_READY(left) == -1 ||
11058 PyUnicode_READY(right) == -1)
11059 return NULL;
11060
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011061 if (left == right) {
11062 switch (op) {
11063 case Py_EQ:
11064 case Py_LE:
11065 case Py_GE:
11066 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011067 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011068 case Py_NE:
11069 case Py_LT:
11070 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011071 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011072 default:
11073 PyErr_BadArgument();
11074 return NULL;
11075 }
11076 }
11077 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011078 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011079 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011080 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011081 }
11082 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011083 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011084 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011085 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011086}
11087
Alexander Belopolsky40018472011-02-26 01:02:56 +000011088int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011089_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11090{
11091 return unicode_eq(aa, bb);
11092}
11093
11094int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011095PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011096{
Victor Stinner77282cb2013-04-14 19:22:47 +020011097 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098 void *buf1, *buf2;
11099 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011100 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011101
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011102 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011103 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011104 "'in <string>' requires string as left operand, not %.100s",
11105 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011106 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011107 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011108 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011109 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011110 if (ensure_unicode(str) < 0)
11111 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011112
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011113 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011114 kind2 = PyUnicode_KIND(substr);
11115 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011116 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011118 len2 = PyUnicode_GET_LENGTH(substr);
11119 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011120 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011121 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011122 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011123 if (len2 == 1) {
11124 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11125 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011126 return result;
11127 }
11128 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011129 buf2 = _PyUnicode_AsKind(substr, kind1);
11130 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011131 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011132 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011133
Victor Stinner77282cb2013-04-14 19:22:47 +020011134 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135 case PyUnicode_1BYTE_KIND:
11136 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11137 break;
11138 case PyUnicode_2BYTE_KIND:
11139 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11140 break;
11141 case PyUnicode_4BYTE_KIND:
11142 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11143 break;
11144 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011145 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011146 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011147
Victor Stinner77282cb2013-04-14 19:22:47 +020011148 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 PyMem_Free(buf2);
11150
Guido van Rossum403d68b2000-03-13 15:55:09 +000011151 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011152}
11153
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154/* Concat to string or Unicode object giving a new Unicode object. */
11155
Alexander Belopolsky40018472011-02-26 01:02:56 +000011156PyObject *
11157PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011159 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011160 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011161 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011163 if (ensure_unicode(left) < 0)
11164 return NULL;
11165
11166 if (!PyUnicode_Check(right)) {
11167 PyErr_Format(PyExc_TypeError,
11168 "can only concatenate str (not \"%.200s\") to str",
11169 right->ob_type->tp_name);
11170 return NULL;
11171 }
11172 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011173 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174
11175 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011176 if (left == unicode_empty)
11177 return PyUnicode_FromObject(right);
11178 if (right == unicode_empty)
11179 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011181 left_len = PyUnicode_GET_LENGTH(left);
11182 right_len = PyUnicode_GET_LENGTH(right);
11183 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011184 PyErr_SetString(PyExc_OverflowError,
11185 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011186 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011187 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011188 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011189
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011190 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11191 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011192 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011195 result = PyUnicode_New(new_len, maxchar);
11196 if (result == NULL)
11197 return NULL;
11198 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11199 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11200 assert(_PyUnicode_CheckConsistency(result, 1));
11201 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202}
11203
Walter Dörwald1ab83302007-05-18 17:15:44 +000011204void
Victor Stinner23e56682011-10-03 03:54:37 +020011205PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011206{
Victor Stinner23e56682011-10-03 03:54:37 +020011207 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011208 Py_UCS4 maxchar, maxchar2;
11209 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011210
11211 if (p_left == NULL) {
11212 if (!PyErr_Occurred())
11213 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011214 return;
11215 }
Victor Stinner23e56682011-10-03 03:54:37 +020011216 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011217 if (right == NULL || left == NULL
11218 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011219 if (!PyErr_Occurred())
11220 PyErr_BadInternalCall();
11221 goto error;
11222 }
11223
Benjamin Petersonbac79492012-01-14 13:34:47 -050011224 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011225 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011226 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011227 goto error;
11228
Victor Stinner488fa492011-12-12 00:01:39 +010011229 /* Shortcuts */
11230 if (left == unicode_empty) {
11231 Py_DECREF(left);
11232 Py_INCREF(right);
11233 *p_left = right;
11234 return;
11235 }
11236 if (right == unicode_empty)
11237 return;
11238
11239 left_len = PyUnicode_GET_LENGTH(left);
11240 right_len = PyUnicode_GET_LENGTH(right);
11241 if (left_len > PY_SSIZE_T_MAX - right_len) {
11242 PyErr_SetString(PyExc_OverflowError,
11243 "strings are too large to concat");
11244 goto error;
11245 }
11246 new_len = left_len + right_len;
11247
11248 if (unicode_modifiable(left)
11249 && PyUnicode_CheckExact(right)
11250 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011251 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11252 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011253 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011254 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011255 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11256 {
11257 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011258 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011259 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011260
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011261 /* copy 'right' into the newly allocated area of 'left' */
11262 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011263 }
Victor Stinner488fa492011-12-12 00:01:39 +010011264 else {
11265 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11266 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011267 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011268
Victor Stinner488fa492011-12-12 00:01:39 +010011269 /* Concat the two Unicode strings */
11270 res = PyUnicode_New(new_len, maxchar);
11271 if (res == NULL)
11272 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011273 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11274 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011275 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011276 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011277 }
11278 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011279 return;
11280
11281error:
Victor Stinner488fa492011-12-12 00:01:39 +010011282 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011283}
11284
11285void
11286PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11287{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011288 PyUnicode_Append(pleft, right);
11289 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011290}
11291
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011292/*
11293Wraps stringlib_parse_args_finds() and additionally ensures that the
11294first argument is a unicode object.
11295*/
11296
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011297static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011298parse_args_finds_unicode(const char * function_name, PyObject *args,
11299 PyObject **substring,
11300 Py_ssize_t *start, Py_ssize_t *end)
11301{
11302 if(stringlib_parse_args_finds(function_name, args, substring,
11303 start, end)) {
11304 if (ensure_unicode(*substring) < 0)
11305 return 0;
11306 return 1;
11307 }
11308 return 0;
11309}
11310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011311PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011312 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011314Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011315string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011316interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011317
11318static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011319unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011321 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011322 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011323 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011325 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326 void *buf1, *buf2;
11327 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011329 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011330 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011331
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 kind1 = PyUnicode_KIND(self);
11333 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011334 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011335 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 len1 = PyUnicode_GET_LENGTH(self);
11338 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011340 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011341 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011342
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011343 buf1 = PyUnicode_DATA(self);
11344 buf2 = PyUnicode_DATA(substring);
11345 if (kind2 != kind1) {
11346 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011347 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011348 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011349 }
11350 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 case PyUnicode_1BYTE_KIND:
11352 iresult = ucs1lib_count(
11353 ((Py_UCS1*)buf1) + start, end - start,
11354 buf2, len2, PY_SSIZE_T_MAX
11355 );
11356 break;
11357 case PyUnicode_2BYTE_KIND:
11358 iresult = ucs2lib_count(
11359 ((Py_UCS2*)buf1) + start, end - start,
11360 buf2, len2, PY_SSIZE_T_MAX
11361 );
11362 break;
11363 case PyUnicode_4BYTE_KIND:
11364 iresult = ucs4lib_count(
11365 ((Py_UCS4*)buf1) + start, end - start,
11366 buf2, len2, PY_SSIZE_T_MAX
11367 );
11368 break;
11369 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011370 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 }
11372
11373 result = PyLong_FromSsize_t(iresult);
11374
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011375 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378 return result;
11379}
11380
INADA Naoki3ae20562017-01-16 20:41:20 +090011381/*[clinic input]
11382str.encode as unicode_encode
11383
11384 encoding: str(c_default="NULL") = 'utf-8'
11385 The encoding in which to encode the string.
11386 errors: str(c_default="NULL") = 'strict'
11387 The error handling scheme to use for encoding errors.
11388 The default is 'strict' meaning that encoding errors raise a
11389 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11390 'xmlcharrefreplace' as well as any other name registered with
11391 codecs.register_error that can handle UnicodeEncodeErrors.
11392
11393Encode the string using the codec registered for encoding.
11394[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395
11396static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011397unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011398/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011400 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011401}
11402
INADA Naoki3ae20562017-01-16 20:41:20 +090011403/*[clinic input]
11404str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405
INADA Naoki3ae20562017-01-16 20:41:20 +090011406 tabsize: int = 8
11407
11408Return a copy where all tab characters are expanded using spaces.
11409
11410If tabsize is not given, a tab size of 8 characters is assumed.
11411[clinic start generated code]*/
11412
11413static PyObject *
11414unicode_expandtabs_impl(PyObject *self, int tabsize)
11415/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011417 Py_ssize_t i, j, line_pos, src_len, incr;
11418 Py_UCS4 ch;
11419 PyObject *u;
11420 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011421 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011422 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423
Antoine Pitrou22425222011-10-04 19:10:51 +020011424 if (PyUnicode_READY(self) == -1)
11425 return NULL;
11426
Thomas Wouters7e474022000-07-16 12:04:32 +000011427 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011428 src_len = PyUnicode_GET_LENGTH(self);
11429 i = j = line_pos = 0;
11430 kind = PyUnicode_KIND(self);
11431 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011432 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011433 for (; i < src_len; i++) {
11434 ch = PyUnicode_READ(kind, src_data, i);
11435 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011436 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011438 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011440 goto overflow;
11441 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011443 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011447 goto overflow;
11448 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 if (ch == '\n' || ch == '\r')
11451 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011453 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011454 if (!found)
11455 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011456
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011458 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459 if (!u)
11460 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011461 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Antoine Pitroue71d5742011-10-04 15:55:09 +020011463 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464
Antoine Pitroue71d5742011-10-04 15:55:09 +020011465 for (; i < src_len; i++) {
11466 ch = PyUnicode_READ(kind, src_data, i);
11467 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011468 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011469 incr = tabsize - (line_pos % tabsize);
11470 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011471 FILL(kind, dest_data, ' ', j, incr);
11472 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011473 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011474 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011476 line_pos++;
11477 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011478 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 if (ch == '\n' || ch == '\r')
11480 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011482 }
11483 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011484 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011485
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011487 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11488 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489}
11490
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011491PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011492 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493\n\
11494Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011495such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496arguments start and end are interpreted as in slice notation.\n\
11497\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011498Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499
11500static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011503 /* initialize variables to prevent gcc warning */
11504 PyObject *substring = NULL;
11505 Py_ssize_t start = 0;
11506 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011507 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011509 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011512 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011515 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 if (result == -2)
11518 return NULL;
11519
Christian Heimes217cfd12007-12-02 14:31:20 +000011520 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521}
11522
11523static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011524unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011526 void *data;
11527 enum PyUnicode_Kind kind;
11528 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011529
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011530 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011531 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011533 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011534 if (PyUnicode_READY(self) == -1) {
11535 return NULL;
11536 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011537 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11538 PyErr_SetString(PyExc_IndexError, "string index out of range");
11539 return NULL;
11540 }
11541 kind = PyUnicode_KIND(self);
11542 data = PyUnicode_DATA(self);
11543 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011544 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545}
11546
Guido van Rossumc2504932007-09-18 19:42:40 +000011547/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011548 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011549static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011550unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551{
Guido van Rossumc2504932007-09-18 19:42:40 +000011552 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011553 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011554
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011555#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011556 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011557#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011558 if (_PyUnicode_HASH(self) != -1)
11559 return _PyUnicode_HASH(self);
11560 if (PyUnicode_READY(self) == -1)
11561 return -1;
11562 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011563 /*
11564 We make the hash of the empty string be 0, rather than using
11565 (prefix ^ suffix), since this slightly obfuscates the hash secret
11566 */
11567 if (len == 0) {
11568 _PyUnicode_HASH(self) = 0;
11569 return 0;
11570 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011571 x = _Py_HashBytes(PyUnicode_DATA(self),
11572 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011573 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011574 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575}
11576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011577PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011578 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011580Return the lowest index in S where substring sub is found, \n\
11581such that sub is contained within S[start:end]. Optional\n\
11582arguments start and end are interpreted as in slice notation.\n\
11583\n\
11584Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585
11586static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011587unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011589 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011590 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011591 PyObject *substring = NULL;
11592 Py_ssize_t start = 0;
11593 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011595 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011598 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011599 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011600
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011601 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011602
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 if (result == -2)
11604 return NULL;
11605
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606 if (result < 0) {
11607 PyErr_SetString(PyExc_ValueError, "substring not found");
11608 return NULL;
11609 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011610
Christian Heimes217cfd12007-12-02 14:31:20 +000011611 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612}
11613
INADA Naoki3ae20562017-01-16 20:41:20 +090011614/*[clinic input]
11615str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616
INADA Naoki3ae20562017-01-16 20:41:20 +090011617Return True if the string is a lowercase string, False otherwise.
11618
11619A string is lowercase if all cased characters in the string are lowercase and
11620there is at least one cased character in the string.
11621[clinic start generated code]*/
11622
11623static PyObject *
11624unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011625/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011627 Py_ssize_t i, length;
11628 int kind;
11629 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630 int cased;
11631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 if (PyUnicode_READY(self) == -1)
11633 return NULL;
11634 length = PyUnicode_GET_LENGTH(self);
11635 kind = PyUnicode_KIND(self);
11636 data = PyUnicode_DATA(self);
11637
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 if (length == 1)
11640 return PyBool_FromLong(
11641 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011643 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011645 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011646
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 for (i = 0; i < length; i++) {
11649 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011650
Benjamin Peterson29060642009-01-31 22:14:21 +000011651 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011652 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011653 else if (!cased && Py_UNICODE_ISLOWER(ch))
11654 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011656 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657}
11658
INADA Naoki3ae20562017-01-16 20:41:20 +090011659/*[clinic input]
11660str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661
INADA Naoki3ae20562017-01-16 20:41:20 +090011662Return True if the string is an uppercase string, False otherwise.
11663
11664A string is uppercase if all cased characters in the string are uppercase and
11665there is at least one cased character in the string.
11666[clinic start generated code]*/
11667
11668static PyObject *
11669unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011670/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 Py_ssize_t i, length;
11673 int kind;
11674 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675 int cased;
11676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677 if (PyUnicode_READY(self) == -1)
11678 return NULL;
11679 length = PyUnicode_GET_LENGTH(self);
11680 kind = PyUnicode_KIND(self);
11681 data = PyUnicode_DATA(self);
11682
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 if (length == 1)
11685 return PyBool_FromLong(
11686 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011688 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011690 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011691
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 for (i = 0; i < length; i++) {
11694 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011695
Benjamin Peterson29060642009-01-31 22:14:21 +000011696 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011697 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011698 else if (!cased && Py_UNICODE_ISUPPER(ch))
11699 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011701 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702}
11703
INADA Naoki3ae20562017-01-16 20:41:20 +090011704/*[clinic input]
11705str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706
INADA Naoki3ae20562017-01-16 20:41:20 +090011707Return True if the string is a title-cased string, False otherwise.
11708
11709In a title-cased string, upper- and title-case characters may only
11710follow uncased characters and lowercase characters only cased ones.
11711[clinic start generated code]*/
11712
11713static PyObject *
11714unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011715/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 Py_ssize_t i, length;
11718 int kind;
11719 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720 int cased, previous_is_cased;
11721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (PyUnicode_READY(self) == -1)
11723 return NULL;
11724 length = PyUnicode_GET_LENGTH(self);
11725 kind = PyUnicode_KIND(self);
11726 data = PyUnicode_DATA(self);
11727
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 if (length == 1) {
11730 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11731 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11732 (Py_UNICODE_ISUPPER(ch) != 0));
11733 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011735 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011737 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011738
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739 cased = 0;
11740 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011741 for (i = 0; i < length; i++) {
11742 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011743
Benjamin Peterson29060642009-01-31 22:14:21 +000011744 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11745 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011746 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 previous_is_cased = 1;
11748 cased = 1;
11749 }
11750 else if (Py_UNICODE_ISLOWER(ch)) {
11751 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011752 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011753 previous_is_cased = 1;
11754 cased = 1;
11755 }
11756 else
11757 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011759 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760}
11761
INADA Naoki3ae20562017-01-16 20:41:20 +090011762/*[clinic input]
11763str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764
INADA Naoki3ae20562017-01-16 20:41:20 +090011765Return True if the string is a whitespace string, False otherwise.
11766
11767A string is whitespace if all characters in the string are whitespace and there
11768is at least one character in the string.
11769[clinic start generated code]*/
11770
11771static PyObject *
11772unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011773/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 Py_ssize_t i, length;
11776 int kind;
11777 void *data;
11778
11779 if (PyUnicode_READY(self) == -1)
11780 return NULL;
11781 length = PyUnicode_GET_LENGTH(self);
11782 kind = PyUnicode_KIND(self);
11783 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011784
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011786 if (length == 1)
11787 return PyBool_FromLong(
11788 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011790 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011792 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011794 for (i = 0; i < length; i++) {
11795 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011796 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011797 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011799 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800}
11801
INADA Naoki3ae20562017-01-16 20:41:20 +090011802/*[clinic input]
11803str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011804
INADA Naoki3ae20562017-01-16 20:41:20 +090011805Return True if the string is an alphabetic string, False otherwise.
11806
11807A string is alphabetic if all characters in the string are alphabetic and there
11808is at least one character in the string.
11809[clinic start generated code]*/
11810
11811static PyObject *
11812unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011813/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011814{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 Py_ssize_t i, length;
11816 int kind;
11817 void *data;
11818
11819 if (PyUnicode_READY(self) == -1)
11820 return NULL;
11821 length = PyUnicode_GET_LENGTH(self);
11822 kind = PyUnicode_KIND(self);
11823 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011824
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011825 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 if (length == 1)
11827 return PyBool_FromLong(
11828 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011829
11830 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011831 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011832 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 for (i = 0; i < length; i++) {
11835 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011836 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011837 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011838 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011839}
11840
INADA Naoki3ae20562017-01-16 20:41:20 +090011841/*[clinic input]
11842str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011843
INADA Naoki3ae20562017-01-16 20:41:20 +090011844Return True if the string is an alpha-numeric string, False otherwise.
11845
11846A string is alpha-numeric if all characters in the string are alpha-numeric and
11847there is at least one character in the string.
11848[clinic start generated code]*/
11849
11850static PyObject *
11851unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011852/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011853{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011854 int kind;
11855 void *data;
11856 Py_ssize_t len, i;
11857
11858 if (PyUnicode_READY(self) == -1)
11859 return NULL;
11860
11861 kind = PyUnicode_KIND(self);
11862 data = PyUnicode_DATA(self);
11863 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011864
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011865 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011866 if (len == 1) {
11867 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11868 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11869 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011870
11871 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011872 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011873 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 for (i = 0; i < len; i++) {
11876 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011877 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011878 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011879 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011880 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011881}
11882
INADA Naoki3ae20562017-01-16 20:41:20 +090011883/*[clinic input]
11884str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885
INADA Naoki3ae20562017-01-16 20:41:20 +090011886Return True if the string is a decimal string, False otherwise.
11887
11888A string is a decimal string if all characters in the string are decimal and
11889there is at least one character in the string.
11890[clinic start generated code]*/
11891
11892static PyObject *
11893unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011894/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 Py_ssize_t i, length;
11897 int kind;
11898 void *data;
11899
11900 if (PyUnicode_READY(self) == -1)
11901 return NULL;
11902 length = PyUnicode_GET_LENGTH(self);
11903 kind = PyUnicode_KIND(self);
11904 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 if (length == 1)
11908 return PyBool_FromLong(
11909 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011911 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011913 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 for (i = 0; i < length; i++) {
11916 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011917 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011919 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920}
11921
INADA Naoki3ae20562017-01-16 20:41:20 +090011922/*[clinic input]
11923str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924
INADA Naoki3ae20562017-01-16 20:41:20 +090011925Return True if the string is a digit string, False otherwise.
11926
11927A string is a digit string if all characters in the string are digits and there
11928is at least one character in the string.
11929[clinic start generated code]*/
11930
11931static PyObject *
11932unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011933/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 Py_ssize_t i, length;
11936 int kind;
11937 void *data;
11938
11939 if (PyUnicode_READY(self) == -1)
11940 return NULL;
11941 length = PyUnicode_GET_LENGTH(self);
11942 kind = PyUnicode_KIND(self);
11943 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 if (length == 1) {
11947 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11948 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11949 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011951 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011953 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 for (i = 0; i < length; i++) {
11956 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011957 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011959 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960}
11961
INADA Naoki3ae20562017-01-16 20:41:20 +090011962/*[clinic input]
11963str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964
INADA Naoki3ae20562017-01-16 20:41:20 +090011965Return True if the string is a numeric string, False otherwise.
11966
11967A string is numeric if all characters in the string are numeric and there is at
11968least one character in the string.
11969[clinic start generated code]*/
11970
11971static PyObject *
11972unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011973/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 Py_ssize_t i, length;
11976 int kind;
11977 void *data;
11978
11979 if (PyUnicode_READY(self) == -1)
11980 return NULL;
11981 length = PyUnicode_GET_LENGTH(self);
11982 kind = PyUnicode_KIND(self);
11983 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011984
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011986 if (length == 1)
11987 return PyBool_FromLong(
11988 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011989
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011990 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011992 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011993
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011994 for (i = 0; i < length; i++) {
11995 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011996 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011998 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011999}
12000
Martin v. Löwis47383402007-08-15 07:32:56 +000012001int
12002PyUnicode_IsIdentifier(PyObject *self)
12003{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 int kind;
12005 void *data;
12006 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012007 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 if (PyUnicode_READY(self) == -1) {
12010 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012011 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012 }
12013
12014 /* Special case for empty strings */
12015 if (PyUnicode_GET_LENGTH(self) == 0)
12016 return 0;
12017 kind = PyUnicode_KIND(self);
12018 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012019
12020 /* PEP 3131 says that the first character must be in
12021 XID_Start and subsequent characters in XID_Continue,
12022 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012023 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012024 letters, digits, underscore). However, given the current
12025 definition of XID_Start and XID_Continue, it is sufficient
12026 to check just for these, except that _ must be allowed
12027 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012028 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012029 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012030 return 0;
12031
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012032 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012034 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012035 return 1;
12036}
12037
INADA Naoki3ae20562017-01-16 20:41:20 +090012038/*[clinic input]
12039str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012040
INADA Naoki3ae20562017-01-16 20:41:20 +090012041Return True if the string is a valid Python identifier, False otherwise.
12042
12043Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12044"class".
12045[clinic start generated code]*/
12046
12047static PyObject *
12048unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012049/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012050{
12051 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12052}
12053
INADA Naoki3ae20562017-01-16 20:41:20 +090012054/*[clinic input]
12055str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012056
INADA Naoki3ae20562017-01-16 20:41:20 +090012057Return True if the string is printable, False otherwise.
12058
12059A string is printable if all of its characters are considered printable in
12060repr() or if it is empty.
12061[clinic start generated code]*/
12062
12063static PyObject *
12064unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012065/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012066{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 Py_ssize_t i, length;
12068 int kind;
12069 void *data;
12070
12071 if (PyUnicode_READY(self) == -1)
12072 return NULL;
12073 length = PyUnicode_GET_LENGTH(self);
12074 kind = PyUnicode_KIND(self);
12075 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012076
12077 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012078 if (length == 1)
12079 return PyBool_FromLong(
12080 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012081
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 for (i = 0; i < length; i++) {
12083 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012084 Py_RETURN_FALSE;
12085 }
12086 }
12087 Py_RETURN_TRUE;
12088}
12089
INADA Naoki3ae20562017-01-16 20:41:20 +090012090/*[clinic input]
12091str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092
INADA Naoki3ae20562017-01-16 20:41:20 +090012093 iterable: object
12094 /
12095
12096Concatenate any number of strings.
12097
Martin Panter91a88662017-01-24 00:30:06 +000012098The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012099The result is returned as a new string.
12100
12101Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12102[clinic start generated code]*/
12103
12104static PyObject *
12105unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012106/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107{
INADA Naoki3ae20562017-01-16 20:41:20 +090012108 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109}
12110
Martin v. Löwis18e16552006-02-15 17:27:45 +000012111static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012112unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 if (PyUnicode_READY(self) == -1)
12115 return -1;
12116 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117}
12118
INADA Naoki3ae20562017-01-16 20:41:20 +090012119/*[clinic input]
12120str.ljust as unicode_ljust
12121
12122 width: Py_ssize_t
12123 fillchar: Py_UCS4 = ' '
12124 /
12125
12126Return a left-justified string of length width.
12127
12128Padding is done using the specified fill character (default is a space).
12129[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130
12131static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012132unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12133/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012135 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012136 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137
Victor Stinnerc4b49542011-12-11 22:44:26 +010012138 if (PyUnicode_GET_LENGTH(self) >= width)
12139 return unicode_result_unchanged(self);
12140
12141 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142}
12143
INADA Naoki3ae20562017-01-16 20:41:20 +090012144/*[clinic input]
12145str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146
INADA Naoki3ae20562017-01-16 20:41:20 +090012147Return a copy of the string converted to lowercase.
12148[clinic start generated code]*/
12149
12150static PyObject *
12151unicode_lower_impl(PyObject *self)
12152/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012154 if (PyUnicode_READY(self) == -1)
12155 return NULL;
12156 if (PyUnicode_IS_ASCII(self))
12157 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012158 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159}
12160
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012161#define LEFTSTRIP 0
12162#define RIGHTSTRIP 1
12163#define BOTHSTRIP 2
12164
12165/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012166static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012167
INADA Naoki3ae20562017-01-16 20:41:20 +090012168#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012169
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012170/* externally visible for str.strip(unicode) */
12171PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012172_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012173{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 void *data;
12175 int kind;
12176 Py_ssize_t i, j, len;
12177 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012178 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12181 return NULL;
12182
12183 kind = PyUnicode_KIND(self);
12184 data = PyUnicode_DATA(self);
12185 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012186 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012187 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12188 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012189 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012190
Benjamin Peterson14339b62009-01-31 16:36:08 +000012191 i = 0;
12192 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012193 while (i < len) {
12194 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12195 if (!BLOOM(sepmask, ch))
12196 break;
12197 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12198 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012199 i++;
12200 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012201 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012202
Benjamin Peterson14339b62009-01-31 16:36:08 +000012203 j = len;
12204 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012205 j--;
12206 while (j >= i) {
12207 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12208 if (!BLOOM(sepmask, ch))
12209 break;
12210 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12211 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012212 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012213 }
12214
Benjamin Peterson29060642009-01-31 22:14:21 +000012215 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012216 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012217
Victor Stinner7931d9a2011-11-04 00:22:48 +010012218 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012219}
12220
12221PyObject*
12222PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12223{
12224 unsigned char *data;
12225 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012226 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012227
Victor Stinnerde636f32011-10-01 03:55:54 +020012228 if (PyUnicode_READY(self) == -1)
12229 return NULL;
12230
Victor Stinner684d5fd2012-05-03 02:32:34 +020012231 length = PyUnicode_GET_LENGTH(self);
12232 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012233
Victor Stinner684d5fd2012-05-03 02:32:34 +020012234 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012235 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236
Victor Stinnerde636f32011-10-01 03:55:54 +020012237 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012238 PyErr_SetString(PyExc_IndexError, "string index out of range");
12239 return NULL;
12240 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012241 if (start >= length || end < start)
12242 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012243
Victor Stinner684d5fd2012-05-03 02:32:34 +020012244 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012245 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012246 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012247 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012248 }
12249 else {
12250 kind = PyUnicode_KIND(self);
12251 data = PyUnicode_1BYTE_DATA(self);
12252 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012253 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012254 length);
12255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257
12258static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012259do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 Py_ssize_t len, i, j;
12262
12263 if (PyUnicode_READY(self) == -1)
12264 return NULL;
12265
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012266 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012267
Victor Stinnercc7af722013-04-09 22:39:24 +020012268 if (PyUnicode_IS_ASCII(self)) {
12269 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12270
12271 i = 0;
12272 if (striptype != RIGHTSTRIP) {
12273 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012274 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012275 if (!_Py_ascii_whitespace[ch])
12276 break;
12277 i++;
12278 }
12279 }
12280
12281 j = len;
12282 if (striptype != LEFTSTRIP) {
12283 j--;
12284 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012285 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012286 if (!_Py_ascii_whitespace[ch])
12287 break;
12288 j--;
12289 }
12290 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012291 }
12292 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012293 else {
12294 int kind = PyUnicode_KIND(self);
12295 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012296
Victor Stinnercc7af722013-04-09 22:39:24 +020012297 i = 0;
12298 if (striptype != RIGHTSTRIP) {
12299 while (i < len) {
12300 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12301 if (!Py_UNICODE_ISSPACE(ch))
12302 break;
12303 i++;
12304 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012305 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012306
12307 j = len;
12308 if (striptype != LEFTSTRIP) {
12309 j--;
12310 while (j >= i) {
12311 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12312 if (!Py_UNICODE_ISSPACE(ch))
12313 break;
12314 j--;
12315 }
12316 j++;
12317 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012318 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012319
Victor Stinner7931d9a2011-11-04 00:22:48 +010012320 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012321}
12322
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012323
12324static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012325do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012326{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012327 if (sep != NULL && sep != Py_None) {
12328 if (PyUnicode_Check(sep))
12329 return _PyUnicode_XStrip(self, striptype, sep);
12330 else {
12331 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012332 "%s arg must be None or str",
12333 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012334 return NULL;
12335 }
12336 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012337
Benjamin Peterson14339b62009-01-31 16:36:08 +000012338 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012339}
12340
12341
INADA Naoki3ae20562017-01-16 20:41:20 +090012342/*[clinic input]
12343str.strip as unicode_strip
12344
12345 chars: object = None
12346 /
12347
Victor Stinner0c4a8282017-01-17 02:21:47 +010012348Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012349
12350If chars is given and not None, remove characters in chars instead.
12351[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012352
12353static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012354unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012355/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012356{
INADA Naoki3ae20562017-01-16 20:41:20 +090012357 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012358}
12359
12360
INADA Naoki3ae20562017-01-16 20:41:20 +090012361/*[clinic input]
12362str.lstrip as unicode_lstrip
12363
12364 chars: object = NULL
12365 /
12366
12367Return a copy of the string with leading whitespace removed.
12368
12369If chars is given and not None, remove characters in chars instead.
12370[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012371
12372static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012373unicode_lstrip_impl(PyObject *self, PyObject *chars)
12374/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012375{
INADA Naoki3ae20562017-01-16 20:41:20 +090012376 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012377}
12378
12379
INADA Naoki3ae20562017-01-16 20:41:20 +090012380/*[clinic input]
12381str.rstrip as unicode_rstrip
12382
12383 chars: object = NULL
12384 /
12385
12386Return a copy of the string with trailing whitespace removed.
12387
12388If chars is given and not None, remove characters in chars instead.
12389[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012390
12391static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012392unicode_rstrip_impl(PyObject *self, PyObject *chars)
12393/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012394{
INADA Naoki3ae20562017-01-16 20:41:20 +090012395 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012396}
12397
12398
Guido van Rossumd57fd912000-03-10 22:53:23 +000012399static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012400unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012401{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012402 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012403 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012404
Serhiy Storchaka05997252013-01-26 12:14:02 +020012405 if (len < 1)
12406 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012407
Victor Stinnerc4b49542011-12-11 22:44:26 +010012408 /* no repeat, return original string */
12409 if (len == 1)
12410 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012411
Benjamin Petersonbac79492012-01-14 13:34:47 -050012412 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012413 return NULL;
12414
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012415 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012416 PyErr_SetString(PyExc_OverflowError,
12417 "repeated string is too long");
12418 return NULL;
12419 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012421
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012422 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012423 if (!u)
12424 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012425 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 if (PyUnicode_GET_LENGTH(str) == 1) {
12428 const int kind = PyUnicode_KIND(str);
12429 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012430 if (kind == PyUnicode_1BYTE_KIND) {
12431 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012432 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012433 }
12434 else if (kind == PyUnicode_2BYTE_KIND) {
12435 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012436 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012437 ucs2[n] = fill_char;
12438 } else {
12439 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12440 assert(kind == PyUnicode_4BYTE_KIND);
12441 for (n = 0; n < len; ++n)
12442 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012443 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012444 }
12445 else {
12446 /* number of characters copied this far */
12447 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012448 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012450 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012451 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012452 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012453 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012454 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012455 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012456 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457 }
12458
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012459 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012460 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461}
12462
Alexander Belopolsky40018472011-02-26 01:02:56 +000012463PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012464PyUnicode_Replace(PyObject *str,
12465 PyObject *substr,
12466 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012467 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012468{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012469 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12470 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012471 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012472 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473}
12474
INADA Naoki3ae20562017-01-16 20:41:20 +090012475/*[clinic input]
12476str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012477
INADA Naoki3ae20562017-01-16 20:41:20 +090012478 old: unicode
12479 new: unicode
12480 count: Py_ssize_t = -1
12481 Maximum number of occurrences to replace.
12482 -1 (the default value) means replace all occurrences.
12483 /
12484
12485Return a copy with all occurrences of substring old replaced by new.
12486
12487If the optional argument count is given, only the first count occurrences are
12488replaced.
12489[clinic start generated code]*/
12490
12491static PyObject *
12492unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12493 Py_ssize_t count)
12494/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012496 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012497 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012498 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499}
12500
Alexander Belopolsky40018472011-02-26 01:02:56 +000012501static PyObject *
12502unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012504 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012505 Py_ssize_t isize;
12506 Py_ssize_t osize, squote, dquote, i, o;
12507 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012508 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012509 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012512 return NULL;
12513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012514 isize = PyUnicode_GET_LENGTH(unicode);
12515 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012517 /* Compute length of output, quote characters, and
12518 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012519 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012520 max = 127;
12521 squote = dquote = 0;
12522 ikind = PyUnicode_KIND(unicode);
12523 for (i = 0; i < isize; i++) {
12524 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012525 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012526 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012527 case '\'': squote++; break;
12528 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012529 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012530 incr = 2;
12531 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 default:
12533 /* Fast-path ASCII */
12534 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012535 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012536 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012537 ;
12538 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012540 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012541 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012543 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012545 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012547 if (osize > PY_SSIZE_T_MAX - incr) {
12548 PyErr_SetString(PyExc_OverflowError,
12549 "string is too long to generate repr");
12550 return NULL;
12551 }
12552 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553 }
12554
12555 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012556 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012558 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012559 if (dquote)
12560 /* Both squote and dquote present. Use squote,
12561 and escape them */
12562 osize += squote;
12563 else
12564 quote = '"';
12565 }
Victor Stinner55c08782013-04-14 18:45:39 +020012566 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567
12568 repr = PyUnicode_New(osize, max);
12569 if (repr == NULL)
12570 return NULL;
12571 okind = PyUnicode_KIND(repr);
12572 odata = PyUnicode_DATA(repr);
12573
12574 PyUnicode_WRITE(okind, odata, 0, quote);
12575 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012576 if (unchanged) {
12577 _PyUnicode_FastCopyCharacters(repr, 1,
12578 unicode, 0,
12579 isize);
12580 }
12581 else {
12582 for (i = 0, o = 1; i < isize; i++) {
12583 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584
Victor Stinner55c08782013-04-14 18:45:39 +020012585 /* Escape quotes and backslashes */
12586 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012587 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012589 continue;
12590 }
12591
12592 /* Map special whitespace to '\t', \n', '\r' */
12593 if (ch == '\t') {
12594 PyUnicode_WRITE(okind, odata, o++, '\\');
12595 PyUnicode_WRITE(okind, odata, o++, 't');
12596 }
12597 else if (ch == '\n') {
12598 PyUnicode_WRITE(okind, odata, o++, '\\');
12599 PyUnicode_WRITE(okind, odata, o++, 'n');
12600 }
12601 else if (ch == '\r') {
12602 PyUnicode_WRITE(okind, odata, o++, '\\');
12603 PyUnicode_WRITE(okind, odata, o++, 'r');
12604 }
12605
12606 /* Map non-printable US ASCII to '\xhh' */
12607 else if (ch < ' ' || ch == 0x7F) {
12608 PyUnicode_WRITE(okind, odata, o++, '\\');
12609 PyUnicode_WRITE(okind, odata, o++, 'x');
12610 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12611 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12612 }
12613
12614 /* Copy ASCII characters as-is */
12615 else if (ch < 0x7F) {
12616 PyUnicode_WRITE(okind, odata, o++, ch);
12617 }
12618
12619 /* Non-ASCII characters */
12620 else {
12621 /* Map Unicode whitespace and control characters
12622 (categories Z* and C* except ASCII space)
12623 */
12624 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12625 PyUnicode_WRITE(okind, odata, o++, '\\');
12626 /* Map 8-bit characters to '\xhh' */
12627 if (ch <= 0xff) {
12628 PyUnicode_WRITE(okind, odata, o++, 'x');
12629 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12630 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12631 }
12632 /* Map 16-bit characters to '\uxxxx' */
12633 else if (ch <= 0xffff) {
12634 PyUnicode_WRITE(okind, odata, o++, 'u');
12635 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12636 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12637 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12638 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12639 }
12640 /* Map 21-bit characters to '\U00xxxxxx' */
12641 else {
12642 PyUnicode_WRITE(okind, odata, o++, 'U');
12643 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12644 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12645 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12646 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12647 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12648 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12649 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12650 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12651 }
12652 }
12653 /* Copy characters as-is */
12654 else {
12655 PyUnicode_WRITE(okind, odata, o++, ch);
12656 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012657 }
12658 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012659 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012661 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012662 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663}
12664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012665PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012666 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667\n\
12668Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012669such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670arguments start and end are interpreted as in slice notation.\n\
12671\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012672Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673
12674static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012677 /* initialize variables to prevent gcc warning */
12678 PyObject *substring = NULL;
12679 Py_ssize_t start = 0;
12680 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012681 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012683 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012684 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012686 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012687 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012688
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012689 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012690
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691 if (result == -2)
12692 return NULL;
12693
Christian Heimes217cfd12007-12-02 14:31:20 +000012694 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695}
12696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012697PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012698 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012700Return the highest index in S where substring sub is found,\n\
12701such that sub is contained within S[start:end]. Optional\n\
12702arguments start and end are interpreted as in slice notation.\n\
12703\n\
12704Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705
12706static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012707unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012709 /* initialize variables to prevent gcc warning */
12710 PyObject *substring = NULL;
12711 Py_ssize_t start = 0;
12712 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012713 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012715 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012716 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012718 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012719 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012720
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012721 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012722
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 if (result == -2)
12724 return NULL;
12725
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726 if (result < 0) {
12727 PyErr_SetString(PyExc_ValueError, "substring not found");
12728 return NULL;
12729 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012730
Christian Heimes217cfd12007-12-02 14:31:20 +000012731 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732}
12733
INADA Naoki3ae20562017-01-16 20:41:20 +090012734/*[clinic input]
12735str.rjust as unicode_rjust
12736
12737 width: Py_ssize_t
12738 fillchar: Py_UCS4 = ' '
12739 /
12740
12741Return a right-justified string of length width.
12742
12743Padding is done using the specified fill character (default is a space).
12744[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
12746static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012747unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12748/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012750 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751 return NULL;
12752
Victor Stinnerc4b49542011-12-11 22:44:26 +010012753 if (PyUnicode_GET_LENGTH(self) >= width)
12754 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755
Victor Stinnerc4b49542011-12-11 22:44:26 +010012756 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757}
12758
Alexander Belopolsky40018472011-02-26 01:02:56 +000012759PyObject *
12760PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012762 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012763 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012765 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766}
12767
INADA Naoki3ae20562017-01-16 20:41:20 +090012768/*[clinic input]
12769str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770
INADA Naoki3ae20562017-01-16 20:41:20 +090012771 sep: object = None
12772 The delimiter according which to split the string.
12773 None (the default value) means split according to any whitespace,
12774 and discard empty strings from the result.
12775 maxsplit: Py_ssize_t = -1
12776 Maximum number of splits to do.
12777 -1 (the default value) means no limit.
12778
12779Return a list of the words in the string, using sep as the delimiter string.
12780[clinic start generated code]*/
12781
12782static PyObject *
12783unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12784/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785{
INADA Naoki3ae20562017-01-16 20:41:20 +090012786 if (sep == Py_None)
12787 return split(self, NULL, maxsplit);
12788 if (PyUnicode_Check(sep))
12789 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012790
12791 PyErr_Format(PyExc_TypeError,
12792 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012793 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012794 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795}
12796
Thomas Wouters477c8d52006-05-27 19:21:47 +000012797PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012798PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012799{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012800 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012801 int kind1, kind2;
12802 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012804
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012805 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012807
Victor Stinner14f8f022011-10-05 20:58:25 +020012808 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810 len1 = PyUnicode_GET_LENGTH(str_obj);
12811 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012812 if (kind1 < kind2 || len1 < len2) {
12813 _Py_INCREF_UNICODE_EMPTY();
12814 if (!unicode_empty)
12815 out = NULL;
12816 else {
12817 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12818 Py_DECREF(unicode_empty);
12819 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012820 return out;
12821 }
12822 buf1 = PyUnicode_DATA(str_obj);
12823 buf2 = PyUnicode_DATA(sep_obj);
12824 if (kind2 != kind1) {
12825 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12826 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012827 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012828 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012830 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012831 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012832 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12833 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12834 else
12835 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 break;
12837 case PyUnicode_2BYTE_KIND:
12838 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12839 break;
12840 case PyUnicode_4BYTE_KIND:
12841 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12842 break;
12843 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012844 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012845 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012846
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012847 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012848 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012849
12850 return out;
12851}
12852
12853
12854PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012855PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012856{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012857 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012858 int kind1, kind2;
12859 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012860 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012861
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012862 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012863 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012864
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012865 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012866 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012867 len1 = PyUnicode_GET_LENGTH(str_obj);
12868 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012869 if (kind1 < kind2 || len1 < len2) {
12870 _Py_INCREF_UNICODE_EMPTY();
12871 if (!unicode_empty)
12872 out = NULL;
12873 else {
12874 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12875 Py_DECREF(unicode_empty);
12876 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012877 return out;
12878 }
12879 buf1 = PyUnicode_DATA(str_obj);
12880 buf2 = PyUnicode_DATA(sep_obj);
12881 if (kind2 != kind1) {
12882 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12883 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012884 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012886
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012887 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012888 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012889 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12890 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12891 else
12892 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012893 break;
12894 case PyUnicode_2BYTE_KIND:
12895 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12896 break;
12897 case PyUnicode_4BYTE_KIND:
12898 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12899 break;
12900 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012901 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012903
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012904 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012905 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012906
12907 return out;
12908}
12909
INADA Naoki3ae20562017-01-16 20:41:20 +090012910/*[clinic input]
12911str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012912
INADA Naoki3ae20562017-01-16 20:41:20 +090012913 sep: object
12914 /
12915
12916Partition the string into three parts using the given separator.
12917
12918This will search for the separator in the string. If the separator is found,
12919returns a 3-tuple containing the part before the separator, the separator
12920itself, and the part after it.
12921
12922If the separator is not found, returns a 3-tuple containing the original string
12923and two empty strings.
12924[clinic start generated code]*/
12925
12926static PyObject *
12927unicode_partition(PyObject *self, PyObject *sep)
12928/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012929{
INADA Naoki3ae20562017-01-16 20:41:20 +090012930 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012931}
12932
INADA Naoki3ae20562017-01-16 20:41:20 +090012933/*[clinic input]
12934str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012935
INADA Naoki3ae20562017-01-16 20:41:20 +090012936Partition the string into three parts using the given separator.
12937
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012938This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012939the separator is found, returns a 3-tuple containing the part before the
12940separator, the separator itself, and the part after it.
12941
12942If the separator is not found, returns a 3-tuple containing two empty strings
12943and the original string.
12944[clinic start generated code]*/
12945
12946static PyObject *
12947unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012948/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012949{
INADA Naoki3ae20562017-01-16 20:41:20 +090012950 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012951}
12952
Alexander Belopolsky40018472011-02-26 01:02:56 +000012953PyObject *
12954PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012955{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012956 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012957 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012958
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012959 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012960}
12961
INADA Naoki3ae20562017-01-16 20:41:20 +090012962/*[clinic input]
12963str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012964
INADA Naoki3ae20562017-01-16 20:41:20 +090012965Return a list of the words in the string, using sep as the delimiter string.
12966
12967Splits are done starting at the end of the string and working to the front.
12968[clinic start generated code]*/
12969
12970static PyObject *
12971unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12972/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012973{
INADA Naoki3ae20562017-01-16 20:41:20 +090012974 if (sep == Py_None)
12975 return rsplit(self, NULL, maxsplit);
12976 if (PyUnicode_Check(sep))
12977 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012978
12979 PyErr_Format(PyExc_TypeError,
12980 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012981 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012982 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012983}
12984
INADA Naoki3ae20562017-01-16 20:41:20 +090012985/*[clinic input]
12986str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000012987
Serhiy Storchaka202fda52017-03-12 10:10:47 +020012988 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090012989
12990Return a list of the lines in the string, breaking at line boundaries.
12991
12992Line breaks are not included in the resulting list unless keepends is given and
12993true.
12994[clinic start generated code]*/
12995
12996static PyObject *
12997unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020012998/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012999{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013000 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013001}
13002
13003static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013004PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013005{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013006 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013007}
13008
INADA Naoki3ae20562017-01-16 20:41:20 +090013009/*[clinic input]
13010str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013011
INADA Naoki3ae20562017-01-16 20:41:20 +090013012Convert uppercase characters to lowercase and lowercase characters to uppercase.
13013[clinic start generated code]*/
13014
13015static PyObject *
13016unicode_swapcase_impl(PyObject *self)
13017/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013018{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013019 if (PyUnicode_READY(self) == -1)
13020 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013021 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013022}
13023
Larry Hastings61272b72014-01-07 12:41:53 -080013024/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013025
Larry Hastings31826802013-10-19 00:09:25 -070013026@staticmethod
13027str.maketrans as unicode_maketrans
13028
13029 x: object
13030
13031 y: unicode=NULL
13032
13033 z: unicode=NULL
13034
13035 /
13036
13037Return a translation table usable for str.translate().
13038
13039If there is only one argument, it must be a dictionary mapping Unicode
13040ordinals (integers) or characters to Unicode ordinals, strings or None.
13041Character keys will be then converted to ordinals.
13042If there are two arguments, they must be strings of equal length, and
13043in the resulting dictionary, each character in x will be mapped to the
13044character at the same position in y. If there is a third argument, it
13045must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013046[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013047
Larry Hastings31826802013-10-19 00:09:25 -070013048static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013049unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013050/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013051{
Georg Brandlceee0772007-11-27 23:48:05 +000013052 PyObject *new = NULL, *key, *value;
13053 Py_ssize_t i = 0;
13054 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013055
Georg Brandlceee0772007-11-27 23:48:05 +000013056 new = PyDict_New();
13057 if (!new)
13058 return NULL;
13059 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013060 int x_kind, y_kind, z_kind;
13061 void *x_data, *y_data, *z_data;
13062
Georg Brandlceee0772007-11-27 23:48:05 +000013063 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013064 if (!PyUnicode_Check(x)) {
13065 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13066 "be a string if there is a second argument");
13067 goto err;
13068 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013069 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013070 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13071 "arguments must have equal length");
13072 goto err;
13073 }
13074 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013075 x_kind = PyUnicode_KIND(x);
13076 y_kind = PyUnicode_KIND(y);
13077 x_data = PyUnicode_DATA(x);
13078 y_data = PyUnicode_DATA(y);
13079 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13080 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013081 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013082 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013083 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013084 if (!value) {
13085 Py_DECREF(key);
13086 goto err;
13087 }
Georg Brandlceee0772007-11-27 23:48:05 +000013088 res = PyDict_SetItem(new, key, value);
13089 Py_DECREF(key);
13090 Py_DECREF(value);
13091 if (res < 0)
13092 goto err;
13093 }
13094 /* create entries for deleting chars in z */
13095 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013096 z_kind = PyUnicode_KIND(z);
13097 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013098 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013099 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013100 if (!key)
13101 goto err;
13102 res = PyDict_SetItem(new, key, Py_None);
13103 Py_DECREF(key);
13104 if (res < 0)
13105 goto err;
13106 }
13107 }
13108 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013109 int kind;
13110 void *data;
13111
Georg Brandlceee0772007-11-27 23:48:05 +000013112 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013113 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013114 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13115 "to maketrans it must be a dict");
13116 goto err;
13117 }
13118 /* copy entries into the new dict, converting string keys to int keys */
13119 while (PyDict_Next(x, &i, &key, &value)) {
13120 if (PyUnicode_Check(key)) {
13121 /* convert string keys to integer keys */
13122 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013123 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013124 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13125 "table must be of length 1");
13126 goto err;
13127 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013128 kind = PyUnicode_KIND(key);
13129 data = PyUnicode_DATA(key);
13130 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013131 if (!newkey)
13132 goto err;
13133 res = PyDict_SetItem(new, newkey, value);
13134 Py_DECREF(newkey);
13135 if (res < 0)
13136 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013137 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013138 /* just keep integer keys */
13139 if (PyDict_SetItem(new, key, value) < 0)
13140 goto err;
13141 } else {
13142 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13143 "be strings or integers");
13144 goto err;
13145 }
13146 }
13147 }
13148 return new;
13149 err:
13150 Py_DECREF(new);
13151 return NULL;
13152}
13153
INADA Naoki3ae20562017-01-16 20:41:20 +090013154/*[clinic input]
13155str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156
INADA Naoki3ae20562017-01-16 20:41:20 +090013157 table: object
13158 Translation table, which must be a mapping of Unicode ordinals to
13159 Unicode ordinals, strings, or None.
13160 /
13161
13162Replace each character in the string using the given translation table.
13163
13164The table must implement lookup/indexing via __getitem__, for instance a
13165dictionary or list. If this operation raises LookupError, the character is
13166left untouched. Characters mapped to None are deleted.
13167[clinic start generated code]*/
13168
13169static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013170unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013171/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013173 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013174}
13175
INADA Naoki3ae20562017-01-16 20:41:20 +090013176/*[clinic input]
13177str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178
INADA Naoki3ae20562017-01-16 20:41:20 +090013179Return a copy of the string converted to uppercase.
13180[clinic start generated code]*/
13181
13182static PyObject *
13183unicode_upper_impl(PyObject *self)
13184/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013185{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013186 if (PyUnicode_READY(self) == -1)
13187 return NULL;
13188 if (PyUnicode_IS_ASCII(self))
13189 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013190 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191}
13192
INADA Naoki3ae20562017-01-16 20:41:20 +090013193/*[clinic input]
13194str.zfill as unicode_zfill
13195
13196 width: Py_ssize_t
13197 /
13198
13199Pad a numeric string with zeros on the left, to fill a field of the given width.
13200
13201The string is never truncated.
13202[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203
13204static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013205unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013206/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013208 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013209 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013210 int kind;
13211 void *data;
13212 Py_UCS4 chr;
13213
Benjamin Petersonbac79492012-01-14 13:34:47 -050013214 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013215 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216
Victor Stinnerc4b49542011-12-11 22:44:26 +010013217 if (PyUnicode_GET_LENGTH(self) >= width)
13218 return unicode_result_unchanged(self);
13219
13220 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221
13222 u = pad(self, fill, 0, '0');
13223
Walter Dörwald068325e2002-04-15 13:36:47 +000013224 if (u == NULL)
13225 return NULL;
13226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013227 kind = PyUnicode_KIND(u);
13228 data = PyUnicode_DATA(u);
13229 chr = PyUnicode_READ(kind, data, fill);
13230
13231 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013233 PyUnicode_WRITE(kind, data, 0, chr);
13234 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013235 }
13236
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013237 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013238 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013239}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240
13241#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013242static PyObject *
13243unicode__decimal2ascii(PyObject *self)
13244{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013245 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013246}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013247#endif
13248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013249PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013250 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013252Return True if S starts with the specified prefix, False otherwise.\n\
13253With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013254With optional end, stop comparing S at that position.\n\
13255prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256
13257static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013258unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013259 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013260{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013261 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013262 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013263 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013264 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013265 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013266
Jesus Ceaac451502011-04-20 17:09:23 +020013267 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013268 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013269 if (PyTuple_Check(subobj)) {
13270 Py_ssize_t i;
13271 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013272 substring = PyTuple_GET_ITEM(subobj, i);
13273 if (!PyUnicode_Check(substring)) {
13274 PyErr_Format(PyExc_TypeError,
13275 "tuple for startswith must only contain str, "
13276 "not %.100s",
13277 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013278 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013279 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013280 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013281 if (result == -1)
13282 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013283 if (result) {
13284 Py_RETURN_TRUE;
13285 }
13286 }
13287 /* nothing matched */
13288 Py_RETURN_FALSE;
13289 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013290 if (!PyUnicode_Check(subobj)) {
13291 PyErr_Format(PyExc_TypeError,
13292 "startswith first arg must be str or "
13293 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013295 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013296 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013297 if (result == -1)
13298 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013299 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013300}
13301
13302
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013303PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013304 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013305\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013306Return True if S ends with the specified suffix, False otherwise.\n\
13307With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013308With optional end, stop comparing S at that position.\n\
13309suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013310
13311static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013312unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013313 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013314{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013315 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013316 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013317 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013318 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013319 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320
Jesus Ceaac451502011-04-20 17:09:23 +020013321 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013322 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013323 if (PyTuple_Check(subobj)) {
13324 Py_ssize_t i;
13325 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013326 substring = PyTuple_GET_ITEM(subobj, i);
13327 if (!PyUnicode_Check(substring)) {
13328 PyErr_Format(PyExc_TypeError,
13329 "tuple for endswith must only contain str, "
13330 "not %.100s",
13331 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013332 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013333 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013334 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013335 if (result == -1)
13336 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013337 if (result) {
13338 Py_RETURN_TRUE;
13339 }
13340 }
13341 Py_RETURN_FALSE;
13342 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013343 if (!PyUnicode_Check(subobj)) {
13344 PyErr_Format(PyExc_TypeError,
13345 "endswith first arg must be str or "
13346 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013348 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013349 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013350 if (result == -1)
13351 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013352 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353}
13354
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013355static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013356_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013357{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013358 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13359 writer->data = PyUnicode_DATA(writer->buffer);
13360
13361 if (!writer->readonly) {
13362 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013363 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013364 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013365 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013366 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13367 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13368 writer->kind = PyUnicode_WCHAR_KIND;
13369 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13370
Victor Stinner8f674cc2013-04-17 23:02:17 +020013371 /* Copy-on-write mode: set buffer size to 0 so
13372 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13373 * next write. */
13374 writer->size = 0;
13375 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013376}
13377
Victor Stinnerd3f08822012-05-29 12:57:52 +020013378void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013379_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013380{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013381 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013382
13383 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013384 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013385
13386 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13387 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13388 writer->kind = PyUnicode_WCHAR_KIND;
13389 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013390}
13391
Victor Stinnerd3f08822012-05-29 12:57:52 +020013392int
13393_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13394 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013395{
13396 Py_ssize_t newlen;
13397 PyObject *newbuffer;
13398
Victor Stinner2740e462016-09-06 16:58:36 -070013399 assert(maxchar <= MAX_UNICODE);
13400
Victor Stinnerca9381e2015-09-22 00:58:32 +020013401 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013402 assert((maxchar > writer->maxchar && length >= 0)
13403 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013404
Victor Stinner202fdca2012-05-07 12:47:02 +020013405 if (length > PY_SSIZE_T_MAX - writer->pos) {
13406 PyErr_NoMemory();
13407 return -1;
13408 }
13409 newlen = writer->pos + length;
13410
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013411 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013412
Victor Stinnerd3f08822012-05-29 12:57:52 +020013413 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013414 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013415 if (writer->overallocate
13416 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13417 /* overallocate to limit the number of realloc() */
13418 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013419 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013420 if (newlen < writer->min_length)
13421 newlen = writer->min_length;
13422
Victor Stinnerd3f08822012-05-29 12:57:52 +020013423 writer->buffer = PyUnicode_New(newlen, maxchar);
13424 if (writer->buffer == NULL)
13425 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013426 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013427 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013428 if (writer->overallocate
13429 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13430 /* overallocate to limit the number of realloc() */
13431 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013432 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013433 if (newlen < writer->min_length)
13434 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013435
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013436 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013437 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013438 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013439 newbuffer = PyUnicode_New(newlen, maxchar);
13440 if (newbuffer == NULL)
13441 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013442 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13443 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013444 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013445 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013446 }
13447 else {
13448 newbuffer = resize_compact(writer->buffer, newlen);
13449 if (newbuffer == NULL)
13450 return -1;
13451 }
13452 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013453 }
13454 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013455 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013456 newbuffer = PyUnicode_New(writer->size, maxchar);
13457 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013458 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013459 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13460 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013461 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013462 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013463 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013464 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013465
13466#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013467}
13468
Victor Stinnerca9381e2015-09-22 00:58:32 +020013469int
13470_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13471 enum PyUnicode_Kind kind)
13472{
13473 Py_UCS4 maxchar;
13474
13475 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13476 assert(writer->kind < kind);
13477
13478 switch (kind)
13479 {
13480 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13481 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13482 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13483 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013484 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013485 }
13486
13487 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13488}
13489
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013490static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013491_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013492{
Victor Stinner2740e462016-09-06 16:58:36 -070013493 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013494 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13495 return -1;
13496 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13497 writer->pos++;
13498 return 0;
13499}
13500
13501int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013502_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13503{
13504 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13505}
13506
13507int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013508_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13509{
13510 Py_UCS4 maxchar;
13511 Py_ssize_t len;
13512
13513 if (PyUnicode_READY(str) == -1)
13514 return -1;
13515 len = PyUnicode_GET_LENGTH(str);
13516 if (len == 0)
13517 return 0;
13518 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13519 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013520 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013521 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013522 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013523 Py_INCREF(str);
13524 writer->buffer = str;
13525 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013526 writer->pos += len;
13527 return 0;
13528 }
13529 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13530 return -1;
13531 }
13532 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13533 str, 0, len);
13534 writer->pos += len;
13535 return 0;
13536}
13537
Victor Stinnere215d962012-10-06 23:03:36 +020013538int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013539_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13540 Py_ssize_t start, Py_ssize_t end)
13541{
13542 Py_UCS4 maxchar;
13543 Py_ssize_t len;
13544
13545 if (PyUnicode_READY(str) == -1)
13546 return -1;
13547
13548 assert(0 <= start);
13549 assert(end <= PyUnicode_GET_LENGTH(str));
13550 assert(start <= end);
13551
13552 if (end == 0)
13553 return 0;
13554
13555 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13556 return _PyUnicodeWriter_WriteStr(writer, str);
13557
13558 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13559 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13560 else
13561 maxchar = writer->maxchar;
13562 len = end - start;
13563
13564 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13565 return -1;
13566
13567 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13568 str, start, len);
13569 writer->pos += len;
13570 return 0;
13571}
13572
13573int
Victor Stinner4a587072013-11-19 12:54:53 +010013574_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13575 const char *ascii, Py_ssize_t len)
13576{
13577 if (len == -1)
13578 len = strlen(ascii);
13579
13580 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13581
13582 if (writer->buffer == NULL && !writer->overallocate) {
13583 PyObject *str;
13584
13585 str = _PyUnicode_FromASCII(ascii, len);
13586 if (str == NULL)
13587 return -1;
13588
13589 writer->readonly = 1;
13590 writer->buffer = str;
13591 _PyUnicodeWriter_Update(writer);
13592 writer->pos += len;
13593 return 0;
13594 }
13595
13596 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13597 return -1;
13598
13599 switch (writer->kind)
13600 {
13601 case PyUnicode_1BYTE_KIND:
13602 {
13603 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13604 Py_UCS1 *data = writer->data;
13605
Christian Heimesf051e432016-09-13 20:22:02 +020013606 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013607 break;
13608 }
13609 case PyUnicode_2BYTE_KIND:
13610 {
13611 _PyUnicode_CONVERT_BYTES(
13612 Py_UCS1, Py_UCS2,
13613 ascii, ascii + len,
13614 (Py_UCS2 *)writer->data + writer->pos);
13615 break;
13616 }
13617 case PyUnicode_4BYTE_KIND:
13618 {
13619 _PyUnicode_CONVERT_BYTES(
13620 Py_UCS1, Py_UCS4,
13621 ascii, ascii + len,
13622 (Py_UCS4 *)writer->data + writer->pos);
13623 break;
13624 }
13625 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013626 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013627 }
13628
13629 writer->pos += len;
13630 return 0;
13631}
13632
13633int
13634_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13635 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013636{
13637 Py_UCS4 maxchar;
13638
13639 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13640 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13641 return -1;
13642 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13643 writer->pos += len;
13644 return 0;
13645}
13646
Victor Stinnerd3f08822012-05-29 12:57:52 +020013647PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013648_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013649{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013650 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013651
Victor Stinnerd3f08822012-05-29 12:57:52 +020013652 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013653 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013654 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013655 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013656
13657 str = writer->buffer;
13658 writer->buffer = NULL;
13659
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013660 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013661 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13662 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013663 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013664
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013665 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13666 PyObject *str2;
13667 str2 = resize_compact(str, writer->pos);
13668 if (str2 == NULL) {
13669 Py_DECREF(str);
13670 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013671 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013672 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013673 }
13674
Victor Stinner15a0bd32013-07-08 22:29:55 +020013675 assert(_PyUnicode_CheckConsistency(str, 1));
13676 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013677}
13678
Victor Stinnerd3f08822012-05-29 12:57:52 +020013679void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013680_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013681{
13682 Py_CLEAR(writer->buffer);
13683}
13684
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013685#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013686
13687PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013688 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013689\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013690Return a formatted version of S, using substitutions from args and kwargs.\n\
13691The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013692
Eric Smith27bbca62010-11-04 17:06:58 +000013693PyDoc_STRVAR(format_map__doc__,
13694 "S.format_map(mapping) -> str\n\
13695\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013696Return a formatted version of S, using substitutions from mapping.\n\
13697The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013698
INADA Naoki3ae20562017-01-16 20:41:20 +090013699/*[clinic input]
13700str.__format__ as unicode___format__
13701
13702 format_spec: unicode
13703 /
13704
13705Return a formatted version of the string as described by format_spec.
13706[clinic start generated code]*/
13707
Eric Smith4a7d76d2008-05-30 18:10:19 +000013708static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013709unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013710/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013711{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013712 _PyUnicodeWriter writer;
13713 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013714
Victor Stinnerd3f08822012-05-29 12:57:52 +020013715 if (PyUnicode_READY(self) == -1)
13716 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013717 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013718 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13719 self, format_spec, 0,
13720 PyUnicode_GET_LENGTH(format_spec));
13721 if (ret == -1) {
13722 _PyUnicodeWriter_Dealloc(&writer);
13723 return NULL;
13724 }
13725 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013726}
13727
INADA Naoki3ae20562017-01-16 20:41:20 +090013728/*[clinic input]
13729str.__sizeof__ as unicode_sizeof
13730
13731Return the size of the string in memory, in bytes.
13732[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013733
13734static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013735unicode_sizeof_impl(PyObject *self)
13736/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013737{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013738 Py_ssize_t size;
13739
13740 /* If it's a compact object, account for base structure +
13741 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013742 if (PyUnicode_IS_COMPACT_ASCII(self))
13743 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13744 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013745 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013746 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013747 else {
13748 /* If it is a two-block object, account for base object, and
13749 for character block if present. */
13750 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013751 if (_PyUnicode_DATA_ANY(self))
13752 size += (PyUnicode_GET_LENGTH(self) + 1) *
13753 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013754 }
13755 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013756 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013757 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13758 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13759 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13760 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013761
13762 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013763}
13764
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013765static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013766unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013767{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013768 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013769 if (!copy)
13770 return NULL;
13771 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013772}
13773
Guido van Rossumd57fd912000-03-10 22:53:23 +000013774static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013775 UNICODE_ENCODE_METHODDEF
13776 UNICODE_REPLACE_METHODDEF
13777 UNICODE_SPLIT_METHODDEF
13778 UNICODE_RSPLIT_METHODDEF
13779 UNICODE_JOIN_METHODDEF
13780 UNICODE_CAPITALIZE_METHODDEF
13781 UNICODE_CASEFOLD_METHODDEF
13782 UNICODE_TITLE_METHODDEF
13783 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013784 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013785 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013786 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013787 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013788 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013789 UNICODE_LJUST_METHODDEF
13790 UNICODE_LOWER_METHODDEF
13791 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013792 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13793 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013794 UNICODE_RJUST_METHODDEF
13795 UNICODE_RSTRIP_METHODDEF
13796 UNICODE_RPARTITION_METHODDEF
13797 UNICODE_SPLITLINES_METHODDEF
13798 UNICODE_STRIP_METHODDEF
13799 UNICODE_SWAPCASE_METHODDEF
13800 UNICODE_TRANSLATE_METHODDEF
13801 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013802 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13803 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013804 UNICODE_ISLOWER_METHODDEF
13805 UNICODE_ISUPPER_METHODDEF
13806 UNICODE_ISTITLE_METHODDEF
13807 UNICODE_ISSPACE_METHODDEF
13808 UNICODE_ISDECIMAL_METHODDEF
13809 UNICODE_ISDIGIT_METHODDEF
13810 UNICODE_ISNUMERIC_METHODDEF
13811 UNICODE_ISALPHA_METHODDEF
13812 UNICODE_ISALNUM_METHODDEF
13813 UNICODE_ISIDENTIFIER_METHODDEF
13814 UNICODE_ISPRINTABLE_METHODDEF
13815 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013816 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013817 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013818 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013819 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013820 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013821#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013822 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013823 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013824#endif
13825
Benjamin Peterson14339b62009-01-31 16:36:08 +000013826 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827 {NULL, NULL}
13828};
13829
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013830static PyObject *
13831unicode_mod(PyObject *v, PyObject *w)
13832{
Brian Curtindfc80e32011-08-10 20:28:54 -050013833 if (!PyUnicode_Check(v))
13834 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013835 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013836}
13837
13838static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013839 0, /*nb_add*/
13840 0, /*nb_subtract*/
13841 0, /*nb_multiply*/
13842 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013843};
13844
Guido van Rossumd57fd912000-03-10 22:53:23 +000013845static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013846 (lenfunc) unicode_length, /* sq_length */
13847 PyUnicode_Concat, /* sq_concat */
13848 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13849 (ssizeargfunc) unicode_getitem, /* sq_item */
13850 0, /* sq_slice */
13851 0, /* sq_ass_item */
13852 0, /* sq_ass_slice */
13853 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013854};
13855
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013856static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013857unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013859 if (PyUnicode_READY(self) == -1)
13860 return NULL;
13861
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013862 if (PyIndex_Check(item)) {
13863 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013864 if (i == -1 && PyErr_Occurred())
13865 return NULL;
13866 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013867 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013868 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013869 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013870 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013871 PyObject *result;
13872 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013873 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013874 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013875
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013876 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013877 return NULL;
13878 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013879 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13880 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013881
13882 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013883 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013884 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013885 slicelength == PyUnicode_GET_LENGTH(self)) {
13886 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013887 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013888 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013889 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013890 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013891 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013892 src_kind = PyUnicode_KIND(self);
13893 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013894 if (!PyUnicode_IS_ASCII(self)) {
13895 kind_limit = kind_maxchar_limit(src_kind);
13896 max_char = 0;
13897 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13898 ch = PyUnicode_READ(src_kind, src_data, cur);
13899 if (ch > max_char) {
13900 max_char = ch;
13901 if (max_char >= kind_limit)
13902 break;
13903 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013904 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013905 }
Victor Stinner55c99112011-10-13 01:17:06 +020013906 else
13907 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013908 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013909 if (result == NULL)
13910 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013911 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013912 dest_data = PyUnicode_DATA(result);
13913
13914 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013915 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13916 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013917 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013918 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013919 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013920 } else {
13921 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13922 return NULL;
13923 }
13924}
13925
13926static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013927 (lenfunc)unicode_length, /* mp_length */
13928 (binaryfunc)unicode_subscript, /* mp_subscript */
13929 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013930};
13931
Guido van Rossumd57fd912000-03-10 22:53:23 +000013932
Guido van Rossumd57fd912000-03-10 22:53:23 +000013933/* Helpers for PyUnicode_Format() */
13934
Victor Stinnera47082312012-10-04 02:19:54 +020013935struct unicode_formatter_t {
13936 PyObject *args;
13937 int args_owned;
13938 Py_ssize_t arglen, argidx;
13939 PyObject *dict;
13940
13941 enum PyUnicode_Kind fmtkind;
13942 Py_ssize_t fmtcnt, fmtpos;
13943 void *fmtdata;
13944 PyObject *fmtstr;
13945
13946 _PyUnicodeWriter writer;
13947};
13948
13949struct unicode_format_arg_t {
13950 Py_UCS4 ch;
13951 int flags;
13952 Py_ssize_t width;
13953 int prec;
13954 int sign;
13955};
13956
Guido van Rossumd57fd912000-03-10 22:53:23 +000013957static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013958unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013959{
Victor Stinnera47082312012-10-04 02:19:54 +020013960 Py_ssize_t argidx = ctx->argidx;
13961
13962 if (argidx < ctx->arglen) {
13963 ctx->argidx++;
13964 if (ctx->arglen < 0)
13965 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013966 else
Victor Stinnera47082312012-10-04 02:19:54 +020013967 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013968 }
13969 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013970 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013971 return NULL;
13972}
13973
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013974/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013975
Victor Stinnera47082312012-10-04 02:19:54 +020013976/* Format a float into the writer if the writer is not NULL, or into *p_output
13977 otherwise.
13978
13979 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013980static int
Victor Stinnera47082312012-10-04 02:19:54 +020013981formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13982 PyObject **p_output,
13983 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013984{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013985 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013986 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013987 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013988 int prec;
13989 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013990
Guido van Rossumd57fd912000-03-10 22:53:23 +000013991 x = PyFloat_AsDouble(v);
13992 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013993 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013994
Victor Stinnera47082312012-10-04 02:19:54 +020013995 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013996 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013997 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013998
Victor Stinnera47082312012-10-04 02:19:54 +020013999 if (arg->flags & F_ALT)
14000 dtoa_flags = Py_DTSF_ALT;
14001 else
14002 dtoa_flags = 0;
14003 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014004 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014005 return -1;
14006 len = strlen(p);
14007 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014008 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014009 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014010 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014011 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014012 }
14013 else
14014 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014015 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014016 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014017}
14018
Victor Stinnerd0880d52012-04-27 23:40:13 +020014019/* formatlong() emulates the format codes d, u, o, x and X, and
14020 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14021 * Python's regular ints.
14022 * Return value: a new PyUnicodeObject*, or NULL if error.
14023 * The output string is of the form
14024 * "-"? ("0x" | "0X")? digit+
14025 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14026 * set in flags. The case of hex digits will be correct,
14027 * There will be at least prec digits, zero-filled on the left if
14028 * necessary to get that many.
14029 * val object to be converted
14030 * flags bitmask of format flags; only F_ALT is looked at
14031 * prec minimum number of digits; 0-fill on left if needed
14032 * type a character in [duoxX]; u acts the same as d
14033 *
14034 * CAUTION: o, x and X conversions on regular ints can never
14035 * produce a '-' sign, but can for Python's unbounded ints.
14036 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014037PyObject *
14038_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014039{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014040 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014041 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014042 Py_ssize_t i;
14043 int sign; /* 1 if '-', else 0 */
14044 int len; /* number of characters */
14045 Py_ssize_t llen;
14046 int numdigits; /* len == numnondigits + numdigits */
14047 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014048
Victor Stinnerd0880d52012-04-27 23:40:13 +020014049 /* Avoid exceeding SSIZE_T_MAX */
14050 if (prec > INT_MAX-3) {
14051 PyErr_SetString(PyExc_OverflowError,
14052 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014053 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014054 }
14055
14056 assert(PyLong_Check(val));
14057
14058 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014059 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014060 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014061 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014062 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014063 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014064 /* int and int subclasses should print numerically when a numeric */
14065 /* format code is used (see issue18780) */
14066 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014067 break;
14068 case 'o':
14069 numnondigits = 2;
14070 result = PyNumber_ToBase(val, 8);
14071 break;
14072 case 'x':
14073 case 'X':
14074 numnondigits = 2;
14075 result = PyNumber_ToBase(val, 16);
14076 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014077 }
14078 if (!result)
14079 return NULL;
14080
14081 assert(unicode_modifiable(result));
14082 assert(PyUnicode_IS_READY(result));
14083 assert(PyUnicode_IS_ASCII(result));
14084
14085 /* To modify the string in-place, there can only be one reference. */
14086 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014087 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014088 PyErr_BadInternalCall();
14089 return NULL;
14090 }
14091 buf = PyUnicode_DATA(result);
14092 llen = PyUnicode_GET_LENGTH(result);
14093 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014094 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014095 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014096 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014097 return NULL;
14098 }
14099 len = (int)llen;
14100 sign = buf[0] == '-';
14101 numnondigits += sign;
14102 numdigits = len - numnondigits;
14103 assert(numdigits > 0);
14104
14105 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014106 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014107 (type == 'o' || type == 'x' || type == 'X'))) {
14108 assert(buf[sign] == '0');
14109 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14110 buf[sign+1] == 'o');
14111 numnondigits -= 2;
14112 buf += 2;
14113 len -= 2;
14114 if (sign)
14115 buf[0] = '-';
14116 assert(len == numnondigits + numdigits);
14117 assert(numdigits > 0);
14118 }
14119
14120 /* Fill with leading zeroes to meet minimum width. */
14121 if (prec > numdigits) {
14122 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14123 numnondigits + prec);
14124 char *b1;
14125 if (!r1) {
14126 Py_DECREF(result);
14127 return NULL;
14128 }
14129 b1 = PyBytes_AS_STRING(r1);
14130 for (i = 0; i < numnondigits; ++i)
14131 *b1++ = *buf++;
14132 for (i = 0; i < prec - numdigits; i++)
14133 *b1++ = '0';
14134 for (i = 0; i < numdigits; i++)
14135 *b1++ = *buf++;
14136 *b1 = '\0';
14137 Py_DECREF(result);
14138 result = r1;
14139 buf = PyBytes_AS_STRING(result);
14140 len = numnondigits + prec;
14141 }
14142
14143 /* Fix up case for hex conversions. */
14144 if (type == 'X') {
14145 /* Need to convert all lower case letters to upper case.
14146 and need to convert 0x to 0X (and -0x to -0X). */
14147 for (i = 0; i < len; i++)
14148 if (buf[i] >= 'a' && buf[i] <= 'x')
14149 buf[i] -= 'a'-'A';
14150 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014151 if (!PyUnicode_Check(result)
14152 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014153 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014154 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014155 Py_DECREF(result);
14156 result = unicode;
14157 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014158 else if (len != PyUnicode_GET_LENGTH(result)) {
14159 if (PyUnicode_Resize(&result, len) < 0)
14160 Py_CLEAR(result);
14161 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014162 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014163}
14164
Ethan Furmandf3ed242014-01-05 06:50:30 -080014165/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014166 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014167 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014168 * -1 and raise an exception on error */
14169static int
Victor Stinnera47082312012-10-04 02:19:54 +020014170mainformatlong(PyObject *v,
14171 struct unicode_format_arg_t *arg,
14172 PyObject **p_output,
14173 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014174{
14175 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014176 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014177
14178 if (!PyNumber_Check(v))
14179 goto wrongtype;
14180
Ethan Furman9ab74802014-03-21 06:38:46 -070014181 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014182 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014183 if (type == 'o' || type == 'x' || type == 'X') {
14184 iobj = PyNumber_Index(v);
14185 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014186 if (PyErr_ExceptionMatches(PyExc_TypeError))
14187 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014188 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014189 }
14190 }
14191 else {
14192 iobj = PyNumber_Long(v);
14193 if (iobj == NULL ) {
14194 if (PyErr_ExceptionMatches(PyExc_TypeError))
14195 goto wrongtype;
14196 return -1;
14197 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014198 }
14199 assert(PyLong_Check(iobj));
14200 }
14201 else {
14202 iobj = v;
14203 Py_INCREF(iobj);
14204 }
14205
14206 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014207 && arg->width == -1 && arg->prec == -1
14208 && !(arg->flags & (F_SIGN | F_BLANK))
14209 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014210 {
14211 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014212 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014213 int base;
14214
Victor Stinnera47082312012-10-04 02:19:54 +020014215 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014216 {
14217 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014218 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014219 case 'd':
14220 case 'i':
14221 case 'u':
14222 base = 10;
14223 break;
14224 case 'o':
14225 base = 8;
14226 break;
14227 case 'x':
14228 case 'X':
14229 base = 16;
14230 break;
14231 }
14232
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014233 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14234 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014235 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014236 }
14237 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014238 return 1;
14239 }
14240
Ethan Furmanb95b5612015-01-23 20:05:18 -080014241 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014242 Py_DECREF(iobj);
14243 if (res == NULL)
14244 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014245 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014246 return 0;
14247
14248wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014249 switch(type)
14250 {
14251 case 'o':
14252 case 'x':
14253 case 'X':
14254 PyErr_Format(PyExc_TypeError,
14255 "%%%c format: an integer is required, "
14256 "not %.200s",
14257 type, Py_TYPE(v)->tp_name);
14258 break;
14259 default:
14260 PyErr_Format(PyExc_TypeError,
14261 "%%%c format: a number is required, "
14262 "not %.200s",
14263 type, Py_TYPE(v)->tp_name);
14264 break;
14265 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014266 return -1;
14267}
14268
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014269static Py_UCS4
14270formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014271{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014272 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014273 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014274 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014275 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014276 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014277 goto onError;
14278 }
14279 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014280 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014281 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014282 /* make sure number is a type of integer */
14283 if (!PyLong_Check(v)) {
14284 iobj = PyNumber_Index(v);
14285 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014286 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014287 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014288 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014289 Py_DECREF(iobj);
14290 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014291 else {
14292 x = PyLong_AsLong(v);
14293 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014294 if (x == -1 && PyErr_Occurred())
14295 goto onError;
14296
Victor Stinner8faf8212011-12-08 22:14:11 +010014297 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014298 PyErr_SetString(PyExc_OverflowError,
14299 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014300 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014301 }
14302
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014303 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014304 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014305
Benjamin Peterson29060642009-01-31 22:14:21 +000014306 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014307 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014308 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014309 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014310}
14311
Victor Stinnera47082312012-10-04 02:19:54 +020014312/* Parse options of an argument: flags, width, precision.
14313 Handle also "%(name)" syntax.
14314
14315 Return 0 if the argument has been formatted into arg->str.
14316 Return 1 if the argument has been written into ctx->writer,
14317 Raise an exception and return -1 on error. */
14318static int
14319unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14320 struct unicode_format_arg_t *arg)
14321{
14322#define FORMAT_READ(ctx) \
14323 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14324
14325 PyObject *v;
14326
Victor Stinnera47082312012-10-04 02:19:54 +020014327 if (arg->ch == '(') {
14328 /* Get argument value from a dictionary. Example: "%(name)s". */
14329 Py_ssize_t keystart;
14330 Py_ssize_t keylen;
14331 PyObject *key;
14332 int pcount = 1;
14333
14334 if (ctx->dict == NULL) {
14335 PyErr_SetString(PyExc_TypeError,
14336 "format requires a mapping");
14337 return -1;
14338 }
14339 ++ctx->fmtpos;
14340 --ctx->fmtcnt;
14341 keystart = ctx->fmtpos;
14342 /* Skip over balanced parentheses */
14343 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14344 arg->ch = FORMAT_READ(ctx);
14345 if (arg->ch == ')')
14346 --pcount;
14347 else if (arg->ch == '(')
14348 ++pcount;
14349 ctx->fmtpos++;
14350 }
14351 keylen = ctx->fmtpos - keystart - 1;
14352 if (ctx->fmtcnt < 0 || pcount > 0) {
14353 PyErr_SetString(PyExc_ValueError,
14354 "incomplete format key");
14355 return -1;
14356 }
14357 key = PyUnicode_Substring(ctx->fmtstr,
14358 keystart, keystart + keylen);
14359 if (key == NULL)
14360 return -1;
14361 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014362 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014363 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014364 }
14365 ctx->args = PyObject_GetItem(ctx->dict, key);
14366 Py_DECREF(key);
14367 if (ctx->args == NULL)
14368 return -1;
14369 ctx->args_owned = 1;
14370 ctx->arglen = -1;
14371 ctx->argidx = -2;
14372 }
14373
14374 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014375 while (--ctx->fmtcnt >= 0) {
14376 arg->ch = FORMAT_READ(ctx);
14377 ctx->fmtpos++;
14378 switch (arg->ch) {
14379 case '-': arg->flags |= F_LJUST; continue;
14380 case '+': arg->flags |= F_SIGN; continue;
14381 case ' ': arg->flags |= F_BLANK; continue;
14382 case '#': arg->flags |= F_ALT; continue;
14383 case '0': arg->flags |= F_ZERO; continue;
14384 }
14385 break;
14386 }
14387
14388 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014389 if (arg->ch == '*') {
14390 v = unicode_format_getnextarg(ctx);
14391 if (v == NULL)
14392 return -1;
14393 if (!PyLong_Check(v)) {
14394 PyErr_SetString(PyExc_TypeError,
14395 "* wants int");
14396 return -1;
14397 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014398 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014399 if (arg->width == -1 && PyErr_Occurred())
14400 return -1;
14401 if (arg->width < 0) {
14402 arg->flags |= F_LJUST;
14403 arg->width = -arg->width;
14404 }
14405 if (--ctx->fmtcnt >= 0) {
14406 arg->ch = FORMAT_READ(ctx);
14407 ctx->fmtpos++;
14408 }
14409 }
14410 else if (arg->ch >= '0' && arg->ch <= '9') {
14411 arg->width = arg->ch - '0';
14412 while (--ctx->fmtcnt >= 0) {
14413 arg->ch = FORMAT_READ(ctx);
14414 ctx->fmtpos++;
14415 if (arg->ch < '0' || arg->ch > '9')
14416 break;
14417 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14418 mixing signed and unsigned comparison. Since arg->ch is between
14419 '0' and '9', casting to int is safe. */
14420 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14421 PyErr_SetString(PyExc_ValueError,
14422 "width too big");
14423 return -1;
14424 }
14425 arg->width = arg->width*10 + (arg->ch - '0');
14426 }
14427 }
14428
14429 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014430 if (arg->ch == '.') {
14431 arg->prec = 0;
14432 if (--ctx->fmtcnt >= 0) {
14433 arg->ch = FORMAT_READ(ctx);
14434 ctx->fmtpos++;
14435 }
14436 if (arg->ch == '*') {
14437 v = unicode_format_getnextarg(ctx);
14438 if (v == NULL)
14439 return -1;
14440 if (!PyLong_Check(v)) {
14441 PyErr_SetString(PyExc_TypeError,
14442 "* wants int");
14443 return -1;
14444 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014445 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014446 if (arg->prec == -1 && PyErr_Occurred())
14447 return -1;
14448 if (arg->prec < 0)
14449 arg->prec = 0;
14450 if (--ctx->fmtcnt >= 0) {
14451 arg->ch = FORMAT_READ(ctx);
14452 ctx->fmtpos++;
14453 }
14454 }
14455 else if (arg->ch >= '0' && arg->ch <= '9') {
14456 arg->prec = arg->ch - '0';
14457 while (--ctx->fmtcnt >= 0) {
14458 arg->ch = FORMAT_READ(ctx);
14459 ctx->fmtpos++;
14460 if (arg->ch < '0' || arg->ch > '9')
14461 break;
14462 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14463 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014464 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014465 return -1;
14466 }
14467 arg->prec = arg->prec*10 + (arg->ch - '0');
14468 }
14469 }
14470 }
14471
14472 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14473 if (ctx->fmtcnt >= 0) {
14474 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14475 if (--ctx->fmtcnt >= 0) {
14476 arg->ch = FORMAT_READ(ctx);
14477 ctx->fmtpos++;
14478 }
14479 }
14480 }
14481 if (ctx->fmtcnt < 0) {
14482 PyErr_SetString(PyExc_ValueError,
14483 "incomplete format");
14484 return -1;
14485 }
14486 return 0;
14487
14488#undef FORMAT_READ
14489}
14490
14491/* Format one argument. Supported conversion specifiers:
14492
14493 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014494 - "i", "d", "u": int or float
14495 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014496 - "e", "E", "f", "F", "g", "G": float
14497 - "c": int or str (1 character)
14498
Victor Stinner8dbd4212012-12-04 09:30:24 +010014499 When possible, the output is written directly into the Unicode writer
14500 (ctx->writer). A string is created when padding is required.
14501
Victor Stinnera47082312012-10-04 02:19:54 +020014502 Return 0 if the argument has been formatted into *p_str,
14503 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014504 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014505static int
14506unicode_format_arg_format(struct unicode_formatter_t *ctx,
14507 struct unicode_format_arg_t *arg,
14508 PyObject **p_str)
14509{
14510 PyObject *v;
14511 _PyUnicodeWriter *writer = &ctx->writer;
14512
14513 if (ctx->fmtcnt == 0)
14514 ctx->writer.overallocate = 0;
14515
Victor Stinnera47082312012-10-04 02:19:54 +020014516 v = unicode_format_getnextarg(ctx);
14517 if (v == NULL)
14518 return -1;
14519
Victor Stinnera47082312012-10-04 02:19:54 +020014520
14521 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014522 case 's':
14523 case 'r':
14524 case 'a':
14525 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14526 /* Fast path */
14527 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14528 return -1;
14529 return 1;
14530 }
14531
14532 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14533 *p_str = v;
14534 Py_INCREF(*p_str);
14535 }
14536 else {
14537 if (arg->ch == 's')
14538 *p_str = PyObject_Str(v);
14539 else if (arg->ch == 'r')
14540 *p_str = PyObject_Repr(v);
14541 else
14542 *p_str = PyObject_ASCII(v);
14543 }
14544 break;
14545
14546 case 'i':
14547 case 'd':
14548 case 'u':
14549 case 'o':
14550 case 'x':
14551 case 'X':
14552 {
14553 int ret = mainformatlong(v, arg, p_str, writer);
14554 if (ret != 0)
14555 return ret;
14556 arg->sign = 1;
14557 break;
14558 }
14559
14560 case 'e':
14561 case 'E':
14562 case 'f':
14563 case 'F':
14564 case 'g':
14565 case 'G':
14566 if (arg->width == -1 && arg->prec == -1
14567 && !(arg->flags & (F_SIGN | F_BLANK)))
14568 {
14569 /* Fast path */
14570 if (formatfloat(v, arg, NULL, writer) == -1)
14571 return -1;
14572 return 1;
14573 }
14574
14575 arg->sign = 1;
14576 if (formatfloat(v, arg, p_str, NULL) == -1)
14577 return -1;
14578 break;
14579
14580 case 'c':
14581 {
14582 Py_UCS4 ch = formatchar(v);
14583 if (ch == (Py_UCS4) -1)
14584 return -1;
14585 if (arg->width == -1 && arg->prec == -1) {
14586 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014587 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014588 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014589 return 1;
14590 }
14591 *p_str = PyUnicode_FromOrdinal(ch);
14592 break;
14593 }
14594
14595 default:
14596 PyErr_Format(PyExc_ValueError,
14597 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014598 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014599 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14600 (int)arg->ch,
14601 ctx->fmtpos - 1);
14602 return -1;
14603 }
14604 if (*p_str == NULL)
14605 return -1;
14606 assert (PyUnicode_Check(*p_str));
14607 return 0;
14608}
14609
14610static int
14611unicode_format_arg_output(struct unicode_formatter_t *ctx,
14612 struct unicode_format_arg_t *arg,
14613 PyObject *str)
14614{
14615 Py_ssize_t len;
14616 enum PyUnicode_Kind kind;
14617 void *pbuf;
14618 Py_ssize_t pindex;
14619 Py_UCS4 signchar;
14620 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014621 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014622 Py_ssize_t sublen;
14623 _PyUnicodeWriter *writer = &ctx->writer;
14624 Py_UCS4 fill;
14625
14626 fill = ' ';
14627 if (arg->sign && arg->flags & F_ZERO)
14628 fill = '0';
14629
14630 if (PyUnicode_READY(str) == -1)
14631 return -1;
14632
14633 len = PyUnicode_GET_LENGTH(str);
14634 if ((arg->width == -1 || arg->width <= len)
14635 && (arg->prec == -1 || arg->prec >= len)
14636 && !(arg->flags & (F_SIGN | F_BLANK)))
14637 {
14638 /* Fast path */
14639 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14640 return -1;
14641 return 0;
14642 }
14643
14644 /* Truncate the string for "s", "r" and "a" formats
14645 if the precision is set */
14646 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14647 if (arg->prec >= 0 && len > arg->prec)
14648 len = arg->prec;
14649 }
14650
14651 /* Adjust sign and width */
14652 kind = PyUnicode_KIND(str);
14653 pbuf = PyUnicode_DATA(str);
14654 pindex = 0;
14655 signchar = '\0';
14656 if (arg->sign) {
14657 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14658 if (ch == '-' || ch == '+') {
14659 signchar = ch;
14660 len--;
14661 pindex++;
14662 }
14663 else if (arg->flags & F_SIGN)
14664 signchar = '+';
14665 else if (arg->flags & F_BLANK)
14666 signchar = ' ';
14667 else
14668 arg->sign = 0;
14669 }
14670 if (arg->width < len)
14671 arg->width = len;
14672
14673 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014674 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014675 if (!(arg->flags & F_LJUST)) {
14676 if (arg->sign) {
14677 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014678 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014679 }
14680 else {
14681 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014682 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014683 }
14684 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014685 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14686 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014687 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014688 }
14689
Victor Stinnera47082312012-10-04 02:19:54 +020014690 buflen = arg->width;
14691 if (arg->sign && len == arg->width)
14692 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014693 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014694 return -1;
14695
14696 /* Write the sign if needed */
14697 if (arg->sign) {
14698 if (fill != ' ') {
14699 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14700 writer->pos += 1;
14701 }
14702 if (arg->width > len)
14703 arg->width--;
14704 }
14705
14706 /* Write the numeric prefix for "x", "X" and "o" formats
14707 if the alternate form is used.
14708 For example, write "0x" for the "%#x" format. */
14709 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14710 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14711 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14712 if (fill != ' ') {
14713 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14714 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14715 writer->pos += 2;
14716 pindex += 2;
14717 }
14718 arg->width -= 2;
14719 if (arg->width < 0)
14720 arg->width = 0;
14721 len -= 2;
14722 }
14723
14724 /* Pad left with the fill character if needed */
14725 if (arg->width > len && !(arg->flags & F_LJUST)) {
14726 sublen = arg->width - len;
14727 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14728 writer->pos += sublen;
14729 arg->width = len;
14730 }
14731
14732 /* If padding with spaces: write sign if needed and/or numeric prefix if
14733 the alternate form is used */
14734 if (fill == ' ') {
14735 if (arg->sign) {
14736 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14737 writer->pos += 1;
14738 }
14739 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14740 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14741 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14742 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14743 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14744 writer->pos += 2;
14745 pindex += 2;
14746 }
14747 }
14748
14749 /* Write characters */
14750 if (len) {
14751 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14752 str, pindex, len);
14753 writer->pos += len;
14754 }
14755
14756 /* Pad right with the fill character if needed */
14757 if (arg->width > len) {
14758 sublen = arg->width - len;
14759 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14760 writer->pos += sublen;
14761 }
14762 return 0;
14763}
14764
14765/* Helper of PyUnicode_Format(): format one arg.
14766 Return 0 on success, raise an exception and return -1 on error. */
14767static int
14768unicode_format_arg(struct unicode_formatter_t *ctx)
14769{
14770 struct unicode_format_arg_t arg;
14771 PyObject *str;
14772 int ret;
14773
Victor Stinner8dbd4212012-12-04 09:30:24 +010014774 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014775 if (arg.ch == '%') {
14776 ctx->fmtpos++;
14777 ctx->fmtcnt--;
14778 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14779 return -1;
14780 return 0;
14781 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014782 arg.flags = 0;
14783 arg.width = -1;
14784 arg.prec = -1;
14785 arg.sign = 0;
14786 str = NULL;
14787
Victor Stinnera47082312012-10-04 02:19:54 +020014788 ret = unicode_format_arg_parse(ctx, &arg);
14789 if (ret == -1)
14790 return -1;
14791
14792 ret = unicode_format_arg_format(ctx, &arg, &str);
14793 if (ret == -1)
14794 return -1;
14795
14796 if (ret != 1) {
14797 ret = unicode_format_arg_output(ctx, &arg, str);
14798 Py_DECREF(str);
14799 if (ret == -1)
14800 return -1;
14801 }
14802
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014803 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014804 PyErr_SetString(PyExc_TypeError,
14805 "not all arguments converted during string formatting");
14806 return -1;
14807 }
14808 return 0;
14809}
14810
Alexander Belopolsky40018472011-02-26 01:02:56 +000014811PyObject *
14812PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014813{
Victor Stinnera47082312012-10-04 02:19:54 +020014814 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014815
Guido van Rossumd57fd912000-03-10 22:53:23 +000014816 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014817 PyErr_BadInternalCall();
14818 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014819 }
Victor Stinnera47082312012-10-04 02:19:54 +020014820
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014821 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014822 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014823
14824 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014825 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14826 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14827 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14828 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014829
Victor Stinner8f674cc2013-04-17 23:02:17 +020014830 _PyUnicodeWriter_Init(&ctx.writer);
14831 ctx.writer.min_length = ctx.fmtcnt + 100;
14832 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014833
Guido van Rossumd57fd912000-03-10 22:53:23 +000014834 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014835 ctx.arglen = PyTuple_Size(args);
14836 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014837 }
14838 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014839 ctx.arglen = -1;
14840 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014841 }
Victor Stinnera47082312012-10-04 02:19:54 +020014842 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014843 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014844 ctx.dict = args;
14845 else
14846 ctx.dict = NULL;
14847 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014848
Victor Stinnera47082312012-10-04 02:19:54 +020014849 while (--ctx.fmtcnt >= 0) {
14850 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014851 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014852
14853 nonfmtpos = ctx.fmtpos++;
14854 while (ctx.fmtcnt >= 0 &&
14855 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14856 ctx.fmtpos++;
14857 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014858 }
Victor Stinnera47082312012-10-04 02:19:54 +020014859 if (ctx.fmtcnt < 0) {
14860 ctx.fmtpos--;
14861 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014862 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014863
Victor Stinnercfc4c132013-04-03 01:48:39 +020014864 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14865 nonfmtpos, ctx.fmtpos) < 0)
14866 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014867 }
14868 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014869 ctx.fmtpos++;
14870 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014871 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014872 }
14873 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014874
Victor Stinnera47082312012-10-04 02:19:54 +020014875 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014876 PyErr_SetString(PyExc_TypeError,
14877 "not all arguments converted during string formatting");
14878 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014879 }
14880
Victor Stinnera47082312012-10-04 02:19:54 +020014881 if (ctx.args_owned) {
14882 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014883 }
Victor Stinnera47082312012-10-04 02:19:54 +020014884 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014885
Benjamin Peterson29060642009-01-31 22:14:21 +000014886 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014887 _PyUnicodeWriter_Dealloc(&ctx.writer);
14888 if (ctx.args_owned) {
14889 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014890 }
14891 return NULL;
14892}
14893
Jeremy Hylton938ace62002-07-17 16:30:39 +000014894static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014895unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14896
Tim Peters6d6c1a32001-08-02 04:15:00 +000014897static PyObject *
14898unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14899{
Benjamin Peterson29060642009-01-31 22:14:21 +000014900 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014901 static char *kwlist[] = {"object", "encoding", "errors", 0};
14902 char *encoding = NULL;
14903 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014904
Benjamin Peterson14339b62009-01-31 16:36:08 +000014905 if (type != &PyUnicode_Type)
14906 return unicode_subtype_new(type, args, kwds);
14907 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014908 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014909 return NULL;
14910 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014911 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014912 if (encoding == NULL && errors == NULL)
14913 return PyObject_Str(x);
14914 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014915 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014916}
14917
Guido van Rossume023fe02001-08-30 03:12:59 +000014918static PyObject *
14919unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14920{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014921 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014922 Py_ssize_t length, char_size;
14923 int share_wstr, share_utf8;
14924 unsigned int kind;
14925 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014926
Benjamin Peterson14339b62009-01-31 16:36:08 +000014927 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014928
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014929 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014930 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014931 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014932 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014933 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014934 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014935 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014936 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014937
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014938 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014939 if (self == NULL) {
14940 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014941 return NULL;
14942 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014943 kind = PyUnicode_KIND(unicode);
14944 length = PyUnicode_GET_LENGTH(unicode);
14945
14946 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014947#ifdef Py_DEBUG
14948 _PyUnicode_HASH(self) = -1;
14949#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014950 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014951#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014952 _PyUnicode_STATE(self).interned = 0;
14953 _PyUnicode_STATE(self).kind = kind;
14954 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014955 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014956 _PyUnicode_STATE(self).ready = 1;
14957 _PyUnicode_WSTR(self) = NULL;
14958 _PyUnicode_UTF8_LENGTH(self) = 0;
14959 _PyUnicode_UTF8(self) = NULL;
14960 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014961 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014962
14963 share_utf8 = 0;
14964 share_wstr = 0;
14965 if (kind == PyUnicode_1BYTE_KIND) {
14966 char_size = 1;
14967 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14968 share_utf8 = 1;
14969 }
14970 else if (kind == PyUnicode_2BYTE_KIND) {
14971 char_size = 2;
14972 if (sizeof(wchar_t) == 2)
14973 share_wstr = 1;
14974 }
14975 else {
14976 assert(kind == PyUnicode_4BYTE_KIND);
14977 char_size = 4;
14978 if (sizeof(wchar_t) == 4)
14979 share_wstr = 1;
14980 }
14981
14982 /* Ensure we won't overflow the length. */
14983 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14984 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014985 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014986 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014987 data = PyObject_MALLOC((length + 1) * char_size);
14988 if (data == NULL) {
14989 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014990 goto onError;
14991 }
14992
Victor Stinnerc3c74152011-10-02 20:39:55 +020014993 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014994 if (share_utf8) {
14995 _PyUnicode_UTF8_LENGTH(self) = length;
14996 _PyUnicode_UTF8(self) = data;
14997 }
14998 if (share_wstr) {
14999 _PyUnicode_WSTR_LENGTH(self) = length;
15000 _PyUnicode_WSTR(self) = (wchar_t *)data;
15001 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015002
Christian Heimesf051e432016-09-13 20:22:02 +020015003 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015004 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015005 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015006#ifdef Py_DEBUG
15007 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15008#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015009 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015010 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015011
15012onError:
15013 Py_DECREF(unicode);
15014 Py_DECREF(self);
15015 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015016}
15017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015018PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015019"str(object='') -> str\n\
15020str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015021\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015022Create a new string object from the given object. If encoding or\n\
15023errors is specified, then the object must expose a data buffer\n\
15024that will be decoded using the given encoding and error handler.\n\
15025Otherwise, returns the result of object.__str__() (if defined)\n\
15026or repr(object).\n\
15027encoding defaults to sys.getdefaultencoding().\n\
15028errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015029
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015030static PyObject *unicode_iter(PyObject *seq);
15031
Guido van Rossumd57fd912000-03-10 22:53:23 +000015032PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015033 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015034 "str", /* tp_name */
15035 sizeof(PyUnicodeObject), /* tp_size */
15036 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015037 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015038 (destructor)unicode_dealloc, /* tp_dealloc */
15039 0, /* tp_print */
15040 0, /* tp_getattr */
15041 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015042 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015043 unicode_repr, /* tp_repr */
15044 &unicode_as_number, /* tp_as_number */
15045 &unicode_as_sequence, /* tp_as_sequence */
15046 &unicode_as_mapping, /* tp_as_mapping */
15047 (hashfunc) unicode_hash, /* tp_hash*/
15048 0, /* tp_call*/
15049 (reprfunc) unicode_str, /* tp_str */
15050 PyObject_GenericGetAttr, /* tp_getattro */
15051 0, /* tp_setattro */
15052 0, /* tp_as_buffer */
15053 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015054 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015055 unicode_doc, /* tp_doc */
15056 0, /* tp_traverse */
15057 0, /* tp_clear */
15058 PyUnicode_RichCompare, /* tp_richcompare */
15059 0, /* tp_weaklistoffset */
15060 unicode_iter, /* tp_iter */
15061 0, /* tp_iternext */
15062 unicode_methods, /* tp_methods */
15063 0, /* tp_members */
15064 0, /* tp_getset */
15065 &PyBaseObject_Type, /* tp_base */
15066 0, /* tp_dict */
15067 0, /* tp_descr_get */
15068 0, /* tp_descr_set */
15069 0, /* tp_dictoffset */
15070 0, /* tp_init */
15071 0, /* tp_alloc */
15072 unicode_new, /* tp_new */
15073 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015074};
15075
15076/* Initialize the Unicode implementation */
15077
Victor Stinner3a50e702011-10-18 21:21:00 +020015078int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015079{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015080 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015081 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015082 0x000A, /* LINE FEED */
15083 0x000D, /* CARRIAGE RETURN */
15084 0x001C, /* FILE SEPARATOR */
15085 0x001D, /* GROUP SEPARATOR */
15086 0x001E, /* RECORD SEPARATOR */
15087 0x0085, /* NEXT LINE */
15088 0x2028, /* LINE SEPARATOR */
15089 0x2029, /* PARAGRAPH SEPARATOR */
15090 };
15091
Fred Drakee4315f52000-05-09 19:53:39 +000015092 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015093 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015094 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015095 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015096 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015097
Guido van Rossumcacfc072002-05-24 19:01:59 +000015098 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015099 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015100
15101 /* initialize the linebreak bloom filter */
15102 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015103 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015104 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015105
Christian Heimes26532f72013-07-20 14:57:16 +020015106 if (PyType_Ready(&EncodingMapType) < 0)
15107 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015108
Benjamin Petersonc4311282012-10-30 23:21:10 -040015109 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15110 Py_FatalError("Can't initialize field name iterator type");
15111
15112 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15113 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015114
Victor Stinner3a50e702011-10-18 21:21:00 +020015115 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015116}
15117
15118/* Finalize the Unicode implementation */
15119
Christian Heimesa156e092008-02-16 07:38:31 +000015120int
15121PyUnicode_ClearFreeList(void)
15122{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015123 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015124}
15125
Guido van Rossumd57fd912000-03-10 22:53:23 +000015126void
Thomas Wouters78890102000-07-22 19:25:51 +000015127_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015128{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015129 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015130
Serhiy Storchaka05997252013-01-26 12:14:02 +020015131 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015132
Serhiy Storchaka05997252013-01-26 12:14:02 +020015133 for (i = 0; i < 256; i++)
15134 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015135 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015136 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015137}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015138
Walter Dörwald16807132007-05-25 13:52:07 +000015139void
15140PyUnicode_InternInPlace(PyObject **p)
15141{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015142 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015143 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015144#ifdef Py_DEBUG
15145 assert(s != NULL);
15146 assert(_PyUnicode_CHECK(s));
15147#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015148 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015149 return;
15150#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015151 /* If it's a subclass, we don't really know what putting
15152 it in the interned dict might do. */
15153 if (!PyUnicode_CheckExact(s))
15154 return;
15155 if (PyUnicode_CHECK_INTERNED(s))
15156 return;
15157 if (interned == NULL) {
15158 interned = PyDict_New();
15159 if (interned == NULL) {
15160 PyErr_Clear(); /* Don't leave an exception */
15161 return;
15162 }
15163 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015164 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015165 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015166 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015167 if (t == NULL) {
15168 PyErr_Clear();
15169 return;
15170 }
15171 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015172 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015173 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015174 return;
15175 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015176 /* The two references in interned are not counted by refcnt.
15177 The deallocator will take care of this */
15178 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015179 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015180}
15181
15182void
15183PyUnicode_InternImmortal(PyObject **p)
15184{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015185 PyUnicode_InternInPlace(p);
15186 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015187 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015188 Py_INCREF(*p);
15189 }
Walter Dörwald16807132007-05-25 13:52:07 +000015190}
15191
15192PyObject *
15193PyUnicode_InternFromString(const char *cp)
15194{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015195 PyObject *s = PyUnicode_FromString(cp);
15196 if (s == NULL)
15197 return NULL;
15198 PyUnicode_InternInPlace(&s);
15199 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015200}
15201
Alexander Belopolsky40018472011-02-26 01:02:56 +000015202void
15203_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015204{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015205 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015206 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015207 Py_ssize_t i, n;
15208 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015209
Benjamin Peterson14339b62009-01-31 16:36:08 +000015210 if (interned == NULL || !PyDict_Check(interned))
15211 return;
15212 keys = PyDict_Keys(interned);
15213 if (keys == NULL || !PyList_Check(keys)) {
15214 PyErr_Clear();
15215 return;
15216 }
Walter Dörwald16807132007-05-25 13:52:07 +000015217
Benjamin Peterson14339b62009-01-31 16:36:08 +000015218 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15219 detector, interned unicode strings are not forcibly deallocated;
15220 rather, we give them their stolen references back, and then clear
15221 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015222
Benjamin Peterson14339b62009-01-31 16:36:08 +000015223 n = PyList_GET_SIZE(keys);
15224 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015225 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015226 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015227 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015228 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015229 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015231 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015232 case SSTATE_NOT_INTERNED:
15233 /* XXX Shouldn't happen */
15234 break;
15235 case SSTATE_INTERNED_IMMORTAL:
15236 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015237 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015238 break;
15239 case SSTATE_INTERNED_MORTAL:
15240 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015241 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015242 break;
15243 default:
15244 Py_FatalError("Inconsistent interned string state.");
15245 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015246 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015247 }
15248 fprintf(stderr, "total size of all interned strings: "
15249 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15250 "mortal/immortal\n", mortal_size, immortal_size);
15251 Py_DECREF(keys);
15252 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015253 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015254}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015255
15256
15257/********************* Unicode Iterator **************************/
15258
15259typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015260 PyObject_HEAD
15261 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015262 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015263} unicodeiterobject;
15264
15265static void
15266unicodeiter_dealloc(unicodeiterobject *it)
15267{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 _PyObject_GC_UNTRACK(it);
15269 Py_XDECREF(it->it_seq);
15270 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015271}
15272
15273static int
15274unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15275{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015276 Py_VISIT(it->it_seq);
15277 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015278}
15279
15280static PyObject *
15281unicodeiter_next(unicodeiterobject *it)
15282{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015283 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015284
Benjamin Peterson14339b62009-01-31 16:36:08 +000015285 assert(it != NULL);
15286 seq = it->it_seq;
15287 if (seq == NULL)
15288 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015289 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015290
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015291 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15292 int kind = PyUnicode_KIND(seq);
15293 void *data = PyUnicode_DATA(seq);
15294 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15295 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015296 if (item != NULL)
15297 ++it->it_index;
15298 return item;
15299 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015300
Benjamin Peterson14339b62009-01-31 16:36:08 +000015301 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015302 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015303 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015304}
15305
15306static PyObject *
15307unicodeiter_len(unicodeiterobject *it)
15308{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015309 Py_ssize_t len = 0;
15310 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015311 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015312 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015313}
15314
15315PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15316
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015317static PyObject *
15318unicodeiter_reduce(unicodeiterobject *it)
15319{
15320 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015321 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015322 it->it_seq, it->it_index);
15323 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015324 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015325 if (u == NULL)
15326 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015327 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015328 }
15329}
15330
15331PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15332
15333static PyObject *
15334unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15335{
15336 Py_ssize_t index = PyLong_AsSsize_t(state);
15337 if (index == -1 && PyErr_Occurred())
15338 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015339 if (it->it_seq != NULL) {
15340 if (index < 0)
15341 index = 0;
15342 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15343 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15344 it->it_index = index;
15345 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015346 Py_RETURN_NONE;
15347}
15348
15349PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15350
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015351static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015352 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015353 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015354 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15355 reduce_doc},
15356 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15357 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015358 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015359};
15360
15361PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015362 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15363 "str_iterator", /* tp_name */
15364 sizeof(unicodeiterobject), /* tp_basicsize */
15365 0, /* tp_itemsize */
15366 /* methods */
15367 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15368 0, /* tp_print */
15369 0, /* tp_getattr */
15370 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015371 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015372 0, /* tp_repr */
15373 0, /* tp_as_number */
15374 0, /* tp_as_sequence */
15375 0, /* tp_as_mapping */
15376 0, /* tp_hash */
15377 0, /* tp_call */
15378 0, /* tp_str */
15379 PyObject_GenericGetAttr, /* tp_getattro */
15380 0, /* tp_setattro */
15381 0, /* tp_as_buffer */
15382 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15383 0, /* tp_doc */
15384 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15385 0, /* tp_clear */
15386 0, /* tp_richcompare */
15387 0, /* tp_weaklistoffset */
15388 PyObject_SelfIter, /* tp_iter */
15389 (iternextfunc)unicodeiter_next, /* tp_iternext */
15390 unicodeiter_methods, /* tp_methods */
15391 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015392};
15393
15394static PyObject *
15395unicode_iter(PyObject *seq)
15396{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015397 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015398
Benjamin Peterson14339b62009-01-31 16:36:08 +000015399 if (!PyUnicode_Check(seq)) {
15400 PyErr_BadInternalCall();
15401 return NULL;
15402 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015403 if (PyUnicode_READY(seq) == -1)
15404 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015405 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15406 if (it == NULL)
15407 return NULL;
15408 it->it_index = 0;
15409 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015410 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015411 _PyObject_GC_TRACK(it);
15412 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015413}
15414
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015415
15416size_t
15417Py_UNICODE_strlen(const Py_UNICODE *u)
15418{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015419 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015420}
15421
15422Py_UNICODE*
15423Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15424{
15425 Py_UNICODE *u = s1;
15426 while ((*u++ = *s2++));
15427 return s1;
15428}
15429
15430Py_UNICODE*
15431Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15432{
15433 Py_UNICODE *u = s1;
15434 while ((*u++ = *s2++))
15435 if (n-- == 0)
15436 break;
15437 return s1;
15438}
15439
15440Py_UNICODE*
15441Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15442{
15443 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015444 u1 += wcslen(u1);
15445 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015446 return s1;
15447}
15448
15449int
15450Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15451{
15452 while (*s1 && *s2 && *s1 == *s2)
15453 s1++, s2++;
15454 if (*s1 && *s2)
15455 return (*s1 < *s2) ? -1 : +1;
15456 if (*s1)
15457 return 1;
15458 if (*s2)
15459 return -1;
15460 return 0;
15461}
15462
15463int
15464Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15465{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015466 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015467 for (; n != 0; n--) {
15468 u1 = *s1;
15469 u2 = *s2;
15470 if (u1 != u2)
15471 return (u1 < u2) ? -1 : +1;
15472 if (u1 == '\0')
15473 return 0;
15474 s1++;
15475 s2++;
15476 }
15477 return 0;
15478}
15479
15480Py_UNICODE*
15481Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15482{
15483 const Py_UNICODE *p;
15484 for (p = s; *p; p++)
15485 if (*p == c)
15486 return (Py_UNICODE*)p;
15487 return NULL;
15488}
15489
15490Py_UNICODE*
15491Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15492{
15493 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015494 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015495 while (p != s) {
15496 p--;
15497 if (*p == c)
15498 return (Py_UNICODE*)p;
15499 }
15500 return NULL;
15501}
Victor Stinner331ea922010-08-10 16:37:20 +000015502
Victor Stinner71133ff2010-09-01 23:43:53 +000015503Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015504PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015505{
Victor Stinner577db2c2011-10-11 22:12:48 +020015506 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015507 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015509 if (!PyUnicode_Check(unicode)) {
15510 PyErr_BadArgument();
15511 return NULL;
15512 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015513 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015514 if (u == NULL)
15515 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015516 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015517 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015518 PyErr_NoMemory();
15519 return NULL;
15520 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015521 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015522 size *= sizeof(Py_UNICODE);
15523 copy = PyMem_Malloc(size);
15524 if (copy == NULL) {
15525 PyErr_NoMemory();
15526 return NULL;
15527 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015528 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015529 return copy;
15530}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015531
Georg Brandl66c221e2010-10-14 07:04:07 +000015532/* A _string module, to export formatter_parser and formatter_field_name_split
15533 to the string.Formatter class implemented in Python. */
15534
15535static PyMethodDef _string_methods[] = {
15536 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15537 METH_O, PyDoc_STR("split the argument as a field name")},
15538 {"formatter_parser", (PyCFunction) formatter_parser,
15539 METH_O, PyDoc_STR("parse the argument as a format string")},
15540 {NULL, NULL}
15541};
15542
15543static struct PyModuleDef _string_module = {
15544 PyModuleDef_HEAD_INIT,
15545 "_string",
15546 PyDoc_STR("string helper module"),
15547 0,
15548 _string_methods,
15549 NULL,
15550 NULL,
15551 NULL,
15552 NULL
15553};
15554
15555PyMODINIT_FUNC
15556PyInit__string(void)
15557{
15558 return PyModule_Create(&_string_module);
15559}
15560
15561
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015562#ifdef __cplusplus
15563}
15564#endif