blob: c7480a0d87c5710f5a4e2afdf3fa596b4ca591e5 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043#include "internal/pystate.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000044#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050045#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070046#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000047
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000048#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000049#include <windows.h>
50#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000051
Larry Hastings61272b72014-01-07 12:41:53 -080052/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090053class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080054[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090055/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
56
57/*[python input]
58class Py_UCS4_converter(CConverter):
59 type = 'Py_UCS4'
60 converter = 'convert_uc'
61
62 def converter_init(self):
63 if self.default is not unspecified:
64 self.c_default = ascii(self.default)
65 if len(self.c_default) > 4 or self.c_default[0] != "'":
66 self.c_default = hex(ord(self.default))
67
68[python start generated code]*/
69/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080070
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000071/* --- Globals ------------------------------------------------------------
72
Serhiy Storchaka05997252013-01-26 12:14:02 +020073NOTE: In the interpreter's initialization phase, some globals are currently
74 initialized dynamically as needed. In the process Unicode objects may
75 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000076
77*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000078
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079
80#ifdef __cplusplus
81extern "C" {
82#endif
83
Victor Stinner8faf8212011-12-08 22:14:11 +010084/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
85#define MAX_UNICODE 0x10ffff
86
Victor Stinner910337b2011-10-03 03:20:16 +020087#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020088# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020089#else
90# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
91#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020092
Victor Stinnere90fe6a2011-10-01 16:48:13 +020093#define _PyUnicode_UTF8(op) \
94 (((PyCompactUnicodeObject*)(op))->utf8)
95#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020096 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020097 assert(PyUnicode_IS_READY(op)), \
98 PyUnicode_IS_COMPACT_ASCII(op) ? \
99 ((char*)((PyASCIIObject*)(op) + 1)) : \
100 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200101#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102 (((PyCompactUnicodeObject*)(op))->utf8_length)
103#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200104 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200105 assert(PyUnicode_IS_READY(op)), \
106 PyUnicode_IS_COMPACT_ASCII(op) ? \
107 ((PyASCIIObject*)(op))->length : \
108 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_WSTR(op) \
110 (((PyASCIIObject*)(op))->wstr)
111#define _PyUnicode_WSTR_LENGTH(op) \
112 (((PyCompactUnicodeObject*)(op))->wstr_length)
113#define _PyUnicode_LENGTH(op) \
114 (((PyASCIIObject *)(op))->length)
115#define _PyUnicode_STATE(op) \
116 (((PyASCIIObject *)(op))->state)
117#define _PyUnicode_HASH(op) \
118 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200119#define _PyUnicode_KIND(op) \
120 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200121 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200122#define _PyUnicode_GET_LENGTH(op) \
123 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200124 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200125#define _PyUnicode_DATA_ANY(op) \
126 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200127
Victor Stinner910337b2011-10-03 03:20:16 +0200128#undef PyUnicode_READY
129#define PyUnicode_READY(op) \
130 (assert(_PyUnicode_CHECK(op)), \
131 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200132 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100133 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200134
Victor Stinnerc379ead2011-10-03 12:52:27 +0200135#define _PyUnicode_SHARE_UTF8(op) \
136 (assert(_PyUnicode_CHECK(op)), \
137 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
138 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
139#define _PyUnicode_SHARE_WSTR(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
142
Victor Stinner829c0ad2011-10-03 01:08:02 +0200143/* true if the Unicode object has an allocated UTF-8 memory block
144 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200145#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200146 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200147 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200148 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
149
Victor Stinner03490912011-10-03 23:45:12 +0200150/* true if the Unicode object has an allocated wstr memory block
151 (not shared with other data) */
152#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200153 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200154 (!PyUnicode_IS_READY(op) || \
155 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
156
Victor Stinner910337b2011-10-03 03:20:16 +0200157/* Generic helper macro to convert characters of different types.
158 from_type and to_type have to be valid type names, begin and end
159 are pointers to the source characters which should be of type
160 "from_type *". to is a pointer of type "to_type *" and points to the
161 buffer where the result characters are written to. */
162#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
163 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100164 to_type *_to = (to_type *)(to); \
165 const from_type *_iter = (from_type *)(begin); \
166 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200167 Py_ssize_t n = (_end) - (_iter); \
168 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200169 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_unrolled_end)) { \
171 _to[0] = (to_type) _iter[0]; \
172 _to[1] = (to_type) _iter[1]; \
173 _to[2] = (to_type) _iter[2]; \
174 _to[3] = (to_type) _iter[3]; \
175 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200176 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200177 while (_iter < (_end)) \
178 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200179 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200180
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200181#ifdef MS_WINDOWS
182 /* On Windows, overallocate by 50% is the best factor */
183# define OVERALLOCATE_FACTOR 2
184#else
185 /* On Linux, overallocate by 25% is the best factor */
186# define OVERALLOCATE_FACTOR 4
187#endif
188
Walter Dörwald16807132007-05-25 13:52:07 +0000189/* This dictionary holds all interned unicode strings. Note that references
190 to strings in this dictionary are *not* counted in the string's ob_refcnt.
191 When the interned string reaches a refcnt of 0 the string deallocation
192 function will delete the reference from this dictionary.
193
194 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000195 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000196*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000198
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200201
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200203 do { \
204 if (unicode_empty != NULL) \
205 Py_INCREF(unicode_empty); \
206 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207 unicode_empty = PyUnicode_New(0, 0); \
208 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200209 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200210 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
211 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200212 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200213 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000214
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215#define _Py_RETURN_UNICODE_EMPTY() \
216 do { \
217 _Py_INCREF_UNICODE_EMPTY(); \
218 return unicode_empty; \
219 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000220
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200221/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700222static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200223_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
224
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200225/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200226static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200227
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000228/* Single character Unicode strings in the Latin-1 range are being
229 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200230static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000231
Christian Heimes190d79e2008-01-30 11:58:22 +0000232/* Fast detection of the most frequent whitespace characters */
233const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000234 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000235/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000236/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000237/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000238/* case 0x000C: * FORM FEED */
239/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000240 0, 1, 1, 1, 1, 1, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000242/* case 0x001C: * FILE SEPARATOR */
243/* case 0x001D: * GROUP SEPARATOR */
244/* case 0x001E: * RECORD SEPARATOR */
245/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000246 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000247/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000248 1, 0, 0, 0, 0, 0, 0, 0,
249 0, 0, 0, 0, 0, 0, 0, 0,
250 0, 0, 0, 0, 0, 0, 0, 0,
251 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000252
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
254 0, 0, 0, 0, 0, 0, 0, 0,
255 0, 0, 0, 0, 0, 0, 0, 0,
256 0, 0, 0, 0, 0, 0, 0, 0,
257 0, 0, 0, 0, 0, 0, 0, 0,
258 0, 0, 0, 0, 0, 0, 0, 0,
259 0, 0, 0, 0, 0, 0, 0, 0,
260 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000261};
262
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200263/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200264static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200265static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100266static int unicode_modifiable(PyObject *unicode);
267
Victor Stinnerfe226c02011-10-03 03:52:20 +0200268
Alexander Belopolsky40018472011-02-26 01:02:56 +0000269static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100270_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200271static PyObject *
272_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
273static PyObject *
274_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
275
276static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000277unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000278 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100279 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000280 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
281
Alexander Belopolsky40018472011-02-26 01:02:56 +0000282static void
283raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300284 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100285 PyObject *unicode,
286 Py_ssize_t startpos, Py_ssize_t endpos,
287 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000288
Christian Heimes190d79e2008-01-30 11:58:22 +0000289/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200290static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000291 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000292/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000293/* 0x000B, * LINE TABULATION */
294/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000295/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000296 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000298/* 0x001C, * FILE SEPARATOR */
299/* 0x001D, * GROUP SEPARATOR */
300/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 0, 0, 0, 0, 1, 1, 1, 0,
302 0, 0, 0, 0, 0, 0, 0, 0,
303 0, 0, 0, 0, 0, 0, 0, 0,
304 0, 0, 0, 0, 0, 0, 0, 0,
305 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000306
Benjamin Peterson14339b62009-01-31 16:36:08 +0000307 0, 0, 0, 0, 0, 0, 0, 0,
308 0, 0, 0, 0, 0, 0, 0, 0,
309 0, 0, 0, 0, 0, 0, 0, 0,
310 0, 0, 0, 0, 0, 0, 0, 0,
311 0, 0, 0, 0, 0, 0, 0, 0,
312 0, 0, 0, 0, 0, 0, 0, 0,
313 0, 0, 0, 0, 0, 0, 0, 0,
314 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000315};
316
INADA Naoki3ae20562017-01-16 20:41:20 +0900317static int convert_uc(PyObject *obj, void *addr);
318
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300319#include "clinic/unicodeobject.c.h"
320
Victor Stinner50149202015-09-22 00:26:54 +0200321typedef enum {
322 _Py_ERROR_UNKNOWN=0,
323 _Py_ERROR_STRICT,
324 _Py_ERROR_SURROGATEESCAPE,
325 _Py_ERROR_REPLACE,
326 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200327 _Py_ERROR_BACKSLASHREPLACE,
328 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200329 _Py_ERROR_XMLCHARREFREPLACE,
330 _Py_ERROR_OTHER
331} _Py_error_handler;
332
333static _Py_error_handler
334get_error_handler(const char *errors)
335{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200337 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200338 }
339 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200341 }
342 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200343 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200344 }
345 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200346 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200347 }
348 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200349 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200350 }
351 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200352 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200353 }
354 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200355 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200356 }
Victor Stinner50149202015-09-22 00:26:54 +0200357 return _Py_ERROR_OTHER;
358}
359
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300360/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
361 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000362Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000363PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000364{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000365#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000366 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000367#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000368 /* This is actually an illegal character, so it should
369 not be passed to unichr. */
370 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000371#endif
372}
373
Victor Stinner910337b2011-10-03 03:20:16 +0200374#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200375int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100376_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200377{
378 PyASCIIObject *ascii;
379 unsigned int kind;
380
381 assert(PyUnicode_Check(op));
382
383 ascii = (PyASCIIObject *)op;
384 kind = ascii->state.kind;
385
Victor Stinnera3b334d2011-10-03 13:53:37 +0200386 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200387 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200388 assert(ascii->state.ready == 1);
389 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200390 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200391 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200392 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200393
Victor Stinnera41463c2011-10-04 01:05:08 +0200394 if (ascii->state.compact == 1) {
395 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200396 assert(kind == PyUnicode_1BYTE_KIND
397 || kind == PyUnicode_2BYTE_KIND
398 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200399 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200400 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200401 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100402 }
403 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200404 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
405
406 data = unicode->data.any;
407 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100408 assert(ascii->length == 0);
409 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200410 assert(ascii->state.compact == 0);
411 assert(ascii->state.ascii == 0);
412 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100413 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200414 assert(ascii->wstr != NULL);
415 assert(data == NULL);
416 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200417 }
418 else {
419 assert(kind == PyUnicode_1BYTE_KIND
420 || kind == PyUnicode_2BYTE_KIND
421 || kind == PyUnicode_4BYTE_KIND);
422 assert(ascii->state.compact == 0);
423 assert(ascii->state.ready == 1);
424 assert(data != NULL);
425 if (ascii->state.ascii) {
426 assert (compact->utf8 == data);
427 assert (compact->utf8_length == ascii->length);
428 }
429 else
430 assert (compact->utf8 != data);
431 }
432 }
433 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200434 if (
435#if SIZEOF_WCHAR_T == 2
436 kind == PyUnicode_2BYTE_KIND
437#else
438 kind == PyUnicode_4BYTE_KIND
439#endif
440 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200441 {
442 assert(ascii->wstr == data);
443 assert(compact->wstr_length == ascii->length);
444 } else
445 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200446 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200447
448 if (compact->utf8 == NULL)
449 assert(compact->utf8_length == 0);
450 if (ascii->wstr == NULL)
451 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200452 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 /* check that the best kind is used */
454 if (check_content && kind != PyUnicode_WCHAR_KIND)
455 {
456 Py_ssize_t i;
457 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200458 void *data;
459 Py_UCS4 ch;
460
461 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200462 for (i=0; i < ascii->length; i++)
463 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200464 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200465 if (ch > maxchar)
466 maxchar = ch;
467 }
468 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100469 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200470 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100471 assert(maxchar <= 255);
472 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200473 else
474 assert(maxchar < 128);
475 }
Victor Stinner77faf692011-11-20 18:56:05 +0100476 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200477 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100478 assert(maxchar <= 0xFFFF);
479 }
480 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200481 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100482 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100483 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200484 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200485 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400486 return 1;
487}
Victor Stinner910337b2011-10-03 03:20:16 +0200488#endif
489
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100490static PyObject*
491unicode_result_wchar(PyObject *unicode)
492{
493#ifndef Py_DEBUG
494 Py_ssize_t len;
495
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 len = _PyUnicode_WSTR_LENGTH(unicode);
497 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100498 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200499 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100500 }
501
502 if (len == 1) {
503 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100504 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100505 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
506 Py_DECREF(unicode);
507 return latin1_char;
508 }
509 }
510
511 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200512 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100513 return NULL;
514 }
515#else
Victor Stinneraa771272012-10-04 02:32:58 +0200516 assert(Py_REFCNT(unicode) == 1);
517
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 /* don't make the result ready in debug mode to ensure that the caller
519 makes the string ready before using it */
520 assert(_PyUnicode_CheckConsistency(unicode, 1));
521#endif
522 return unicode;
523}
524
525static PyObject*
526unicode_result_ready(PyObject *unicode)
527{
528 Py_ssize_t length;
529
530 length = PyUnicode_GET_LENGTH(unicode);
531 if (length == 0) {
532 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100533 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200534 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100535 }
536 return unicode_empty;
537 }
538
539 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200540 void *data = PyUnicode_DATA(unicode);
541 int kind = PyUnicode_KIND(unicode);
542 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100543 if (ch < 256) {
544 PyObject *latin1_char = unicode_latin1[ch];
545 if (latin1_char != NULL) {
546 if (unicode != latin1_char) {
547 Py_INCREF(latin1_char);
548 Py_DECREF(unicode);
549 }
550 return latin1_char;
551 }
552 else {
553 assert(_PyUnicode_CheckConsistency(unicode, 1));
554 Py_INCREF(unicode);
555 unicode_latin1[ch] = unicode;
556 return unicode;
557 }
558 }
559 }
560
561 assert(_PyUnicode_CheckConsistency(unicode, 1));
562 return unicode;
563}
564
565static PyObject*
566unicode_result(PyObject *unicode)
567{
568 assert(_PyUnicode_CHECK(unicode));
569 if (PyUnicode_IS_READY(unicode))
570 return unicode_result_ready(unicode);
571 else
572 return unicode_result_wchar(unicode);
573}
574
Victor Stinnerc4b49542011-12-11 22:44:26 +0100575static PyObject*
576unicode_result_unchanged(PyObject *unicode)
577{
578 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500579 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100580 return NULL;
581 Py_INCREF(unicode);
582 return unicode;
583 }
584 else
585 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100586 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100587}
588
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200589/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
590 ASCII, Latin1, UTF-8, etc. */
591static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200592backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200593 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
594{
Victor Stinnerad771582015-10-09 12:38:53 +0200595 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200596 Py_UCS4 ch;
597 enum PyUnicode_Kind kind;
598 void *data;
599
600 assert(PyUnicode_IS_READY(unicode));
601 kind = PyUnicode_KIND(unicode);
602 data = PyUnicode_DATA(unicode);
603
604 size = 0;
605 /* determine replacement size */
606 for (i = collstart; i < collend; ++i) {
607 Py_ssize_t incr;
608
609 ch = PyUnicode_READ(kind, data, i);
610 if (ch < 0x100)
611 incr = 2+2;
612 else if (ch < 0x10000)
613 incr = 2+4;
614 else {
615 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200616 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200617 }
618 if (size > PY_SSIZE_T_MAX - incr) {
619 PyErr_SetString(PyExc_OverflowError,
620 "encoded result is too long for a Python string");
621 return NULL;
622 }
623 size += incr;
624 }
625
Victor Stinnerad771582015-10-09 12:38:53 +0200626 str = _PyBytesWriter_Prepare(writer, str, size);
627 if (str == NULL)
628 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200629
630 /* generate replacement */
631 for (i = collstart; i < collend; ++i) {
632 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200633 *str++ = '\\';
634 if (ch >= 0x00010000) {
635 *str++ = 'U';
636 *str++ = Py_hexdigits[(ch>>28)&0xf];
637 *str++ = Py_hexdigits[(ch>>24)&0xf];
638 *str++ = Py_hexdigits[(ch>>20)&0xf];
639 *str++ = Py_hexdigits[(ch>>16)&0xf];
640 *str++ = Py_hexdigits[(ch>>12)&0xf];
641 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200642 }
Victor Stinner797485e2015-10-09 03:17:30 +0200643 else if (ch >= 0x100) {
644 *str++ = 'u';
645 *str++ = Py_hexdigits[(ch>>12)&0xf];
646 *str++ = Py_hexdigits[(ch>>8)&0xf];
647 }
648 else
649 *str++ = 'x';
650 *str++ = Py_hexdigits[(ch>>4)&0xf];
651 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200652 }
653 return str;
654}
655
656/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
657 ASCII, Latin1, UTF-8, etc. */
658static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200659xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200660 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
661{
Victor Stinnerad771582015-10-09 12:38:53 +0200662 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200663 Py_UCS4 ch;
664 enum PyUnicode_Kind kind;
665 void *data;
666
667 assert(PyUnicode_IS_READY(unicode));
668 kind = PyUnicode_KIND(unicode);
669 data = PyUnicode_DATA(unicode);
670
671 size = 0;
672 /* determine replacement size */
673 for (i = collstart; i < collend; ++i) {
674 Py_ssize_t incr;
675
676 ch = PyUnicode_READ(kind, data, i);
677 if (ch < 10)
678 incr = 2+1+1;
679 else if (ch < 100)
680 incr = 2+2+1;
681 else if (ch < 1000)
682 incr = 2+3+1;
683 else if (ch < 10000)
684 incr = 2+4+1;
685 else if (ch < 100000)
686 incr = 2+5+1;
687 else if (ch < 1000000)
688 incr = 2+6+1;
689 else {
690 assert(ch <= MAX_UNICODE);
691 incr = 2+7+1;
692 }
693 if (size > PY_SSIZE_T_MAX - incr) {
694 PyErr_SetString(PyExc_OverflowError,
695 "encoded result is too long for a Python string");
696 return NULL;
697 }
698 size += incr;
699 }
700
Victor Stinnerad771582015-10-09 12:38:53 +0200701 str = _PyBytesWriter_Prepare(writer, str, size);
702 if (str == NULL)
703 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200704
705 /* generate replacement */
706 for (i = collstart; i < collend; ++i) {
707 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
708 }
709 return str;
710}
711
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712/* --- Bloom Filters ----------------------------------------------------- */
713
714/* stuff to implement simple "bloom filters" for Unicode characters.
715 to keep things simple, we use a single bitmask, using the least 5
716 bits from each unicode characters as the bit index. */
717
718/* the linebreak mask is set up by Unicode_Init below */
719
Antoine Pitrouf068f942010-01-13 14:19:12 +0000720#if LONG_BIT >= 128
721#define BLOOM_WIDTH 128
722#elif LONG_BIT >= 64
723#define BLOOM_WIDTH 64
724#elif LONG_BIT >= 32
725#define BLOOM_WIDTH 32
726#else
727#error "LONG_BIT is smaller than 32"
728#endif
729
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730#define BLOOM_MASK unsigned long
731
Serhiy Storchaka05997252013-01-26 12:14:02 +0200732static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733
Antoine Pitrouf068f942010-01-13 14:19:12 +0000734#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735
Benjamin Peterson29060642009-01-31 22:14:21 +0000736#define BLOOM_LINEBREAK(ch) \
737 ((ch) < 128U ? ascii_linebreak[(ch)] : \
738 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000739
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700740static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200741make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742{
Victor Stinnera85af502013-04-09 21:53:54 +0200743#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
744 do { \
745 TYPE *data = (TYPE *)PTR; \
746 TYPE *end = data + LEN; \
747 Py_UCS4 ch; \
748 for (; data != end; data++) { \
749 ch = *data; \
750 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
751 } \
752 break; \
753 } while (0)
754
Thomas Wouters477c8d52006-05-27 19:21:47 +0000755 /* calculate simple bloom-style bitmask for a given unicode string */
756
Antoine Pitrouf068f942010-01-13 14:19:12 +0000757 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758
759 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200760 switch (kind) {
761 case PyUnicode_1BYTE_KIND:
762 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
763 break;
764 case PyUnicode_2BYTE_KIND:
765 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
766 break;
767 case PyUnicode_4BYTE_KIND:
768 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
769 break;
770 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700771 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200772 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000773 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200774
775#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776}
777
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300778static int
779ensure_unicode(PyObject *obj)
780{
781 if (!PyUnicode_Check(obj)) {
782 PyErr_Format(PyExc_TypeError,
783 "must be str, not %.100s",
784 Py_TYPE(obj)->tp_name);
785 return -1;
786 }
787 return PyUnicode_READY(obj);
788}
789
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200790/* Compilation of templated routines */
791
792#include "stringlib/asciilib.h"
793#include "stringlib/fastsearch.h"
794#include "stringlib/partition.h"
795#include "stringlib/split.h"
796#include "stringlib/count.h"
797#include "stringlib/find.h"
798#include "stringlib/find_max_char.h"
799#include "stringlib/localeutil.h"
800#include "stringlib/undef.h"
801
802#include "stringlib/ucs1lib.h"
803#include "stringlib/fastsearch.h"
804#include "stringlib/partition.h"
805#include "stringlib/split.h"
806#include "stringlib/count.h"
807#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300808#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200809#include "stringlib/find_max_char.h"
810#include "stringlib/localeutil.h"
811#include "stringlib/undef.h"
812
813#include "stringlib/ucs2lib.h"
814#include "stringlib/fastsearch.h"
815#include "stringlib/partition.h"
816#include "stringlib/split.h"
817#include "stringlib/count.h"
818#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300819#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200820#include "stringlib/find_max_char.h"
821#include "stringlib/localeutil.h"
822#include "stringlib/undef.h"
823
824#include "stringlib/ucs4lib.h"
825#include "stringlib/fastsearch.h"
826#include "stringlib/partition.h"
827#include "stringlib/split.h"
828#include "stringlib/count.h"
829#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300830#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200831#include "stringlib/find_max_char.h"
832#include "stringlib/localeutil.h"
833#include "stringlib/undef.h"
834
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200835#include "stringlib/unicodedefs.h"
836#include "stringlib/fastsearch.h"
837#include "stringlib/count.h"
838#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100839#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200840
Guido van Rossumd57fd912000-03-10 22:53:23 +0000841/* --- Unicode Object ----------------------------------------------------- */
842
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700843static inline Py_ssize_t
844findchar(const void *s, int kind,
845 Py_ssize_t size, Py_UCS4 ch,
846 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200847{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200848 switch (kind) {
849 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if ((Py_UCS1) ch != ch)
851 return -1;
852 if (direction > 0)
853 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
854 else
855 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200856 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200857 if ((Py_UCS2) ch != ch)
858 return -1;
859 if (direction > 0)
860 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
861 else
862 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200863 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200864 if (direction > 0)
865 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
866 else
867 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200868 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700869 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200871}
872
Victor Stinnerafffce42012-10-03 23:03:17 +0200873#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000874/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200875 earlier.
876
877 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
878 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
879 invalid character in Unicode 6.0. */
880static void
881unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
882{
883 int kind = PyUnicode_KIND(unicode);
884 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
885 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
886 if (length <= old_length)
887 return;
888 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
889}
890#endif
891
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892static PyObject*
893resize_compact(PyObject *unicode, Py_ssize_t length)
894{
895 Py_ssize_t char_size;
896 Py_ssize_t struct_size;
897 Py_ssize_t new_size;
898 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100899 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200900#ifdef Py_DEBUG
901 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
902#endif
903
Victor Stinner79891572012-05-03 13:43:07 +0200904 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200905 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100906 assert(PyUnicode_IS_COMPACT(unicode));
907
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200908 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100909 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200910 struct_size = sizeof(PyASCIIObject);
911 else
912 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200913 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200914
Victor Stinnerfe226c02011-10-03 03:52:20 +0200915 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
916 PyErr_NoMemory();
917 return NULL;
918 }
919 new_size = (struct_size + (length + 1) * char_size);
920
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200921 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
922 PyObject_DEL(_PyUnicode_UTF8(unicode));
923 _PyUnicode_UTF8(unicode) = NULL;
924 _PyUnicode_UTF8_LENGTH(unicode) = 0;
925 }
Victor Stinner84def372011-12-11 20:04:56 +0100926 _Py_DEC_REFTOTAL;
927 _Py_ForgetReference(unicode);
928
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300929 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100930 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100931 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 PyErr_NoMemory();
933 return NULL;
934 }
Victor Stinner84def372011-12-11 20:04:56 +0100935 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200936 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100937
Victor Stinnerfe226c02011-10-03 03:52:20 +0200938 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200939 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100941 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200942 _PyUnicode_WSTR_LENGTH(unicode) = length;
943 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100944 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
945 PyObject_DEL(_PyUnicode_WSTR(unicode));
946 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100947 if (!PyUnicode_IS_ASCII(unicode))
948 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100949 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200950#ifdef Py_DEBUG
951 unicode_fill_invalid(unicode, old_length);
952#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
954 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200955 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200956 return unicode;
957}
958
Alexander Belopolsky40018472011-02-26 01:02:56 +0000959static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200960resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000961{
Victor Stinner95663112011-10-04 01:03:50 +0200962 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100963 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200964 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000966
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967 if (PyUnicode_IS_READY(unicode)) {
968 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200969 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200970 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200971#ifdef Py_DEBUG
972 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
973#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200974
975 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200976 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200977 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
978 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979
980 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
981 PyErr_NoMemory();
982 return -1;
983 }
984 new_size = (length + 1) * char_size;
985
Victor Stinner7a9105a2011-12-12 00:13:42 +0100986 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
987 {
988 PyObject_DEL(_PyUnicode_UTF8(unicode));
989 _PyUnicode_UTF8(unicode) = NULL;
990 _PyUnicode_UTF8_LENGTH(unicode) = 0;
991 }
992
Victor Stinnerfe226c02011-10-03 03:52:20 +0200993 data = (PyObject *)PyObject_REALLOC(data, new_size);
994 if (data == NULL) {
995 PyErr_NoMemory();
996 return -1;
997 }
998 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200999 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001000 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001001 _PyUnicode_WSTR_LENGTH(unicode) = length;
1002 }
1003 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001004 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001005 _PyUnicode_UTF8_LENGTH(unicode) = length;
1006 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001007 _PyUnicode_LENGTH(unicode) = length;
1008 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001009#ifdef Py_DEBUG
1010 unicode_fill_invalid(unicode, old_length);
1011#endif
Victor Stinner95663112011-10-04 01:03:50 +02001012 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001013 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001014 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001015 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001016 }
Victor Stinner95663112011-10-04 01:03:50 +02001017 assert(_PyUnicode_WSTR(unicode) != NULL);
1018
1019 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001020 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001021 PyErr_NoMemory();
1022 return -1;
1023 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001024 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001025 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001026 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001027 if (!wstr) {
1028 PyErr_NoMemory();
1029 return -1;
1030 }
1031 _PyUnicode_WSTR(unicode) = wstr;
1032 _PyUnicode_WSTR(unicode)[length] = 0;
1033 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001034 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001035 return 0;
1036}
1037
Victor Stinnerfe226c02011-10-03 03:52:20 +02001038static PyObject*
1039resize_copy(PyObject *unicode, Py_ssize_t length)
1040{
1041 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001042 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001043 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001045 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046
1047 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1048 if (copy == NULL)
1049 return NULL;
1050
1051 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001052 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001054 }
1055 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001056 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001057
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001058 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001059 if (w == NULL)
1060 return NULL;
1061 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1062 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001063 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001064 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001065 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001066 }
1067}
1068
Guido van Rossumd57fd912000-03-10 22:53:23 +00001069/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001070 Ux0000 terminated; some code (e.g. new_identifier)
1071 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072
1073 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001074 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075
1076*/
1077
Alexander Belopolsky40018472011-02-26 01:02:56 +00001078static PyUnicodeObject *
1079_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001080{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001081 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001083
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 if (length == 0 && unicode_empty != NULL) {
1086 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001087 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001088 }
1089
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001090 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001091 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001092 return (PyUnicodeObject *)PyErr_NoMemory();
1093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001094 if (length < 0) {
1095 PyErr_SetString(PyExc_SystemError,
1096 "Negative size passed to _PyUnicode_New");
1097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001098 }
1099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1101 if (unicode == NULL)
1102 return NULL;
1103 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001104
1105 _PyUnicode_WSTR_LENGTH(unicode) = length;
1106 _PyUnicode_HASH(unicode) = -1;
1107 _PyUnicode_STATE(unicode).interned = 0;
1108 _PyUnicode_STATE(unicode).kind = 0;
1109 _PyUnicode_STATE(unicode).compact = 0;
1110 _PyUnicode_STATE(unicode).ready = 0;
1111 _PyUnicode_STATE(unicode).ascii = 0;
1112 _PyUnicode_DATA_ANY(unicode) = NULL;
1113 _PyUnicode_LENGTH(unicode) = 0;
1114 _PyUnicode_UTF8(unicode) = NULL;
1115 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1118 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001119 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001120 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001121 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123
Jeremy Hyltond8082792003-09-16 19:41:39 +00001124 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001125 * the caller fails before initializing str -- unicode_resize()
1126 * reads str[0], and the Keep-Alive optimization can keep memory
1127 * allocated for str alive across a call to unicode_dealloc(unicode).
1128 * We don't want unicode_resize to read uninitialized memory in
1129 * that case.
1130 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131 _PyUnicode_WSTR(unicode)[0] = 0;
1132 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001133
Victor Stinner7931d9a2011-11-04 00:22:48 +01001134 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001135 return unicode;
1136}
1137
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138static const char*
1139unicode_kind_name(PyObject *unicode)
1140{
Victor Stinner42dfd712011-10-03 14:41:45 +02001141 /* don't check consistency: unicode_kind_name() is called from
1142 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001143 if (!PyUnicode_IS_COMPACT(unicode))
1144 {
1145 if (!PyUnicode_IS_READY(unicode))
1146 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001147 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001148 {
1149 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001150 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 return "legacy ascii";
1152 else
1153 return "legacy latin1";
1154 case PyUnicode_2BYTE_KIND:
1155 return "legacy UCS2";
1156 case PyUnicode_4BYTE_KIND:
1157 return "legacy UCS4";
1158 default:
1159 return "<legacy invalid kind>";
1160 }
1161 }
1162 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001163 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001164 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001165 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001166 return "ascii";
1167 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001168 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001169 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001170 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001171 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001172 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001173 default:
1174 return "<invalid compact kind>";
1175 }
1176}
1177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001179/* Functions wrapping macros for use in debugger */
1180char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001181 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001182}
1183
1184void *_PyUnicode_compact_data(void *unicode) {
1185 return _PyUnicode_COMPACT_DATA(unicode);
1186}
1187void *_PyUnicode_data(void *unicode){
1188 printf("obj %p\n", unicode);
1189 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1190 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1191 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1192 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1193 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1194 return PyUnicode_DATA(unicode);
1195}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001196
1197void
1198_PyUnicode_Dump(PyObject *op)
1199{
1200 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001201 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1202 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1203 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001206 {
1207 if (ascii->state.ascii)
1208 data = (ascii + 1);
1209 else
1210 data = (compact + 1);
1211 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001212 else
1213 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001214 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1215 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001216
Victor Stinnera849a4b2011-10-03 12:12:11 +02001217 if (ascii->wstr == data)
1218 printf("shared ");
1219 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001220
Victor Stinnera3b334d2011-10-03 13:53:37 +02001221 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001222 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001223 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1224 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001225 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1226 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001227 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001228 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001229}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001230#endif
1231
1232PyObject *
1233PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1234{
1235 PyObject *obj;
1236 PyCompactUnicodeObject *unicode;
1237 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001238 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001239 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001240 Py_ssize_t char_size;
1241 Py_ssize_t struct_size;
1242
1243 /* Optimization for empty strings */
1244 if (size == 0 && unicode_empty != NULL) {
1245 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001246 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 }
1248
Victor Stinner9e9d6892011-10-04 01:02:02 +02001249 is_ascii = 0;
1250 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 struct_size = sizeof(PyCompactUnicodeObject);
1252 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001253 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254 char_size = 1;
1255 is_ascii = 1;
1256 struct_size = sizeof(PyASCIIObject);
1257 }
1258 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001259 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 char_size = 1;
1261 }
1262 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001263 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 char_size = 2;
1265 if (sizeof(wchar_t) == 2)
1266 is_sharing = 1;
1267 }
1268 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001269 if (maxchar > MAX_UNICODE) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "invalid maximum character passed to PyUnicode_New");
1272 return NULL;
1273 }
Victor Stinner8f825062012-04-27 13:55:39 +02001274 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 char_size = 4;
1276 if (sizeof(wchar_t) == 4)
1277 is_sharing = 1;
1278 }
1279
1280 /* Ensure we won't overflow the size. */
1281 if (size < 0) {
1282 PyErr_SetString(PyExc_SystemError,
1283 "Negative size passed to PyUnicode_New");
1284 return NULL;
1285 }
1286 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1287 return PyErr_NoMemory();
1288
1289 /* Duplicated allocation code from _PyObject_New() instead of a call to
1290 * PyObject_New() so we are able to allocate space for the object and
1291 * it's data buffer.
1292 */
1293 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1294 if (obj == NULL)
1295 return PyErr_NoMemory();
1296 obj = PyObject_INIT(obj, &PyUnicode_Type);
1297 if (obj == NULL)
1298 return NULL;
1299
1300 unicode = (PyCompactUnicodeObject *)obj;
1301 if (is_ascii)
1302 data = ((PyASCIIObject*)obj) + 1;
1303 else
1304 data = unicode + 1;
1305 _PyUnicode_LENGTH(unicode) = size;
1306 _PyUnicode_HASH(unicode) = -1;
1307 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001308 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309 _PyUnicode_STATE(unicode).compact = 1;
1310 _PyUnicode_STATE(unicode).ready = 1;
1311 _PyUnicode_STATE(unicode).ascii = is_ascii;
1312 if (is_ascii) {
1313 ((char*)data)[size] = 0;
1314 _PyUnicode_WSTR(unicode) = NULL;
1315 }
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((char*)data)[size] = 0;
1318 _PyUnicode_WSTR(unicode) = NULL;
1319 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001321 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001322 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 else {
1324 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001325 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001326 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001328 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001329 ((Py_UCS4*)data)[size] = 0;
1330 if (is_sharing) {
1331 _PyUnicode_WSTR_LENGTH(unicode) = size;
1332 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1333 }
1334 else {
1335 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1336 _PyUnicode_WSTR(unicode) = NULL;
1337 }
1338 }
Victor Stinner8f825062012-04-27 13:55:39 +02001339#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001340 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001341#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001342 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 return obj;
1344}
1345
1346#if SIZEOF_WCHAR_T == 2
1347/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1348 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001349 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350
1351 This function assumes that unicode can hold one more code point than wstr
1352 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001353static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001355 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356{
1357 const wchar_t *iter;
1358 Py_UCS4 *ucs4_out;
1359
Victor Stinner910337b2011-10-03 03:20:16 +02001360 assert(unicode != NULL);
1361 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1363 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1364
1365 for (iter = begin; iter < end; ) {
1366 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1367 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001368 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1369 && (iter+1) < end
1370 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 {
Victor Stinner551ac952011-11-29 22:58:13 +01001372 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373 iter += 2;
1374 }
1375 else {
1376 *ucs4_out++ = *iter;
1377 iter++;
1378 }
1379 }
1380 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1381 _PyUnicode_GET_LENGTH(unicode)));
1382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383}
1384#endif
1385
Victor Stinnercd9950f2011-10-02 00:34:53 +02001386static int
Victor Stinner488fa492011-12-12 00:01:39 +01001387unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001388{
Victor Stinner488fa492011-12-12 00:01:39 +01001389 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001390 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001391 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001392 return -1;
1393 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001394 return 0;
1395}
1396
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397static int
1398_copy_characters(PyObject *to, Py_ssize_t to_start,
1399 PyObject *from, Py_ssize_t from_start,
1400 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001402 unsigned int from_kind, to_kind;
1403 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404
Victor Stinneree4544c2012-05-09 22:24:08 +02001405 assert(0 <= how_many);
1406 assert(0 <= from_start);
1407 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001408 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001409 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001410 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerd3f08822012-05-29 12:57:52 +02001412 assert(PyUnicode_Check(to));
1413 assert(PyUnicode_IS_READY(to));
1414 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1415
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001416 if (how_many == 0)
1417 return 0;
1418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001420 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001422 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423
Victor Stinnerf1852262012-06-16 16:38:26 +02001424#ifdef Py_DEBUG
1425 if (!check_maxchar
1426 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1427 {
1428 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1429 Py_UCS4 ch;
1430 Py_ssize_t i;
1431 for (i=0; i < how_many; i++) {
1432 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1433 assert(ch <= to_maxchar);
1434 }
1435 }
1436#endif
1437
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001438 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001439 if (check_maxchar
1440 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1441 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001442 /* Writing Latin-1 characters into an ASCII string requires to
1443 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001444 Py_UCS4 max_char;
1445 max_char = ucs1lib_find_max_char(from_data,
1446 (Py_UCS1*)from_data + how_many);
1447 if (max_char >= 128)
1448 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001449 }
Christian Heimesf051e432016-09-13 20:22:02 +02001450 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001451 (char*)from_data + from_kind * from_start,
1452 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001454 else if (from_kind == PyUnicode_1BYTE_KIND
1455 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001456 {
1457 _PyUnicode_CONVERT_BYTES(
1458 Py_UCS1, Py_UCS2,
1459 PyUnicode_1BYTE_DATA(from) + from_start,
1460 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1461 PyUnicode_2BYTE_DATA(to) + to_start
1462 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001463 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001464 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001465 && to_kind == PyUnicode_4BYTE_KIND)
1466 {
1467 _PyUnicode_CONVERT_BYTES(
1468 Py_UCS1, Py_UCS4,
1469 PyUnicode_1BYTE_DATA(from) + from_start,
1470 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1471 PyUnicode_4BYTE_DATA(to) + to_start
1472 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001473 }
1474 else if (from_kind == PyUnicode_2BYTE_KIND
1475 && to_kind == PyUnicode_4BYTE_KIND)
1476 {
1477 _PyUnicode_CONVERT_BYTES(
1478 Py_UCS2, Py_UCS4,
1479 PyUnicode_2BYTE_DATA(from) + from_start,
1480 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1481 PyUnicode_4BYTE_DATA(to) + to_start
1482 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001483 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001484 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001485 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1486
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001487 if (!check_maxchar) {
1488 if (from_kind == PyUnicode_2BYTE_KIND
1489 && to_kind == PyUnicode_1BYTE_KIND)
1490 {
1491 _PyUnicode_CONVERT_BYTES(
1492 Py_UCS2, Py_UCS1,
1493 PyUnicode_2BYTE_DATA(from) + from_start,
1494 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1495 PyUnicode_1BYTE_DATA(to) + to_start
1496 );
1497 }
1498 else if (from_kind == PyUnicode_4BYTE_KIND
1499 && to_kind == PyUnicode_1BYTE_KIND)
1500 {
1501 _PyUnicode_CONVERT_BYTES(
1502 Py_UCS4, Py_UCS1,
1503 PyUnicode_4BYTE_DATA(from) + from_start,
1504 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1505 PyUnicode_1BYTE_DATA(to) + to_start
1506 );
1507 }
1508 else if (from_kind == PyUnicode_4BYTE_KIND
1509 && to_kind == PyUnicode_2BYTE_KIND)
1510 {
1511 _PyUnicode_CONVERT_BYTES(
1512 Py_UCS4, Py_UCS2,
1513 PyUnicode_4BYTE_DATA(from) + from_start,
1514 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1515 PyUnicode_2BYTE_DATA(to) + to_start
1516 );
1517 }
1518 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001519 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001520 }
1521 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001522 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001523 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001524 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001525 Py_ssize_t i;
1526
Victor Stinnera0702ab2011-09-29 14:14:38 +02001527 for (i=0; i < how_many; i++) {
1528 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001529 if (ch > to_maxchar)
1530 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001531 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1532 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001533 }
1534 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001535 return 0;
1536}
1537
Victor Stinnerd3f08822012-05-29 12:57:52 +02001538void
1539_PyUnicode_FastCopyCharacters(
1540 PyObject *to, Py_ssize_t to_start,
1541 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001542{
1543 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1544}
1545
1546Py_ssize_t
1547PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1548 PyObject *from, Py_ssize_t from_start,
1549 Py_ssize_t how_many)
1550{
1551 int err;
1552
1553 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1554 PyErr_BadInternalCall();
1555 return -1;
1556 }
1557
Benjamin Petersonbac79492012-01-14 13:34:47 -05001558 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001559 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001560 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001561 return -1;
1562
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001563 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001564 PyErr_SetString(PyExc_IndexError, "string index out of range");
1565 return -1;
1566 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001567 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001568 PyErr_SetString(PyExc_IndexError, "string index out of range");
1569 return -1;
1570 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001571 if (how_many < 0) {
1572 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1573 return -1;
1574 }
1575 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1577 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001578 "Cannot write %zi characters at %zi "
1579 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001580 how_many, to_start, PyUnicode_GET_LENGTH(to));
1581 return -1;
1582 }
1583
1584 if (how_many == 0)
1585 return 0;
1586
Victor Stinner488fa492011-12-12 00:01:39 +01001587 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001588 return -1;
1589
1590 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1591 if (err) {
1592 PyErr_Format(PyExc_SystemError,
1593 "Cannot copy %s characters "
1594 "into a string of %s characters",
1595 unicode_kind_name(from),
1596 unicode_kind_name(to));
1597 return -1;
1598 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001599 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600}
1601
Victor Stinner17222162011-09-28 22:15:37 +02001602/* Find the maximum code point and count the number of surrogate pairs so a
1603 correct string length can be computed before converting a string to UCS4.
1604 This function counts single surrogates as a character and not as a pair.
1605
1606 Return 0 on success, or -1 on error. */
1607static int
1608find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1609 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610{
1611 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001612 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001613
Victor Stinnerc53be962011-10-02 21:33:54 +02001614 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 *num_surrogates = 0;
1616 *maxchar = 0;
1617
1618 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001619#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001620 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1621 && (iter+1) < end
1622 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1623 {
1624 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1625 ++(*num_surrogates);
1626 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 }
1628 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001629#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001630 {
1631 ch = *iter;
1632 iter++;
1633 }
1634 if (ch > *maxchar) {
1635 *maxchar = ch;
1636 if (*maxchar > MAX_UNICODE) {
1637 PyErr_Format(PyExc_ValueError,
1638 "character U+%x is not in range [U+0000; U+10ffff]",
1639 ch);
1640 return -1;
1641 }
1642 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643 }
1644 return 0;
1645}
1646
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001647int
1648_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649{
1650 wchar_t *end;
1651 Py_UCS4 maxchar = 0;
1652 Py_ssize_t num_surrogates;
1653#if SIZEOF_WCHAR_T == 2
1654 Py_ssize_t length_wo_surrogates;
1655#endif
1656
Georg Brandl7597add2011-10-05 16:36:47 +02001657 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001658 strings were created using _PyObject_New() and where no canonical
1659 representation (the str field) has been set yet aka strings
1660 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001661 assert(_PyUnicode_CHECK(unicode));
1662 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001663 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001664 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001665 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001666 /* Actually, it should neither be interned nor be anything else: */
1667 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001670 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001671 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001673
1674 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001675 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1676 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001677 PyErr_NoMemory();
1678 return -1;
1679 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001680 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001681 _PyUnicode_WSTR(unicode), end,
1682 PyUnicode_1BYTE_DATA(unicode));
1683 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1684 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1685 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1686 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001687 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001688 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001689 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 }
1691 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001692 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001693 _PyUnicode_UTF8(unicode) = NULL;
1694 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001695 }
1696 PyObject_FREE(_PyUnicode_WSTR(unicode));
1697 _PyUnicode_WSTR(unicode) = NULL;
1698 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1699 }
1700 /* In this case we might have to convert down from 4-byte native
1701 wchar_t to 2-byte unicode. */
1702 else if (maxchar < 65536) {
1703 assert(num_surrogates == 0 &&
1704 "FindMaxCharAndNumSurrogatePairs() messed up");
1705
Victor Stinner506f5922011-09-28 22:34:18 +02001706#if SIZEOF_WCHAR_T == 2
1707 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001708 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001709 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1710 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1711 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001712 _PyUnicode_UTF8(unicode) = NULL;
1713 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001714#else
1715 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001716 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001717 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001718 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001719 PyErr_NoMemory();
1720 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 }
Victor Stinner506f5922011-09-28 22:34:18 +02001722 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1723 _PyUnicode_WSTR(unicode), end,
1724 PyUnicode_2BYTE_DATA(unicode));
1725 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1726 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1727 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001728 _PyUnicode_UTF8(unicode) = NULL;
1729 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001730 PyObject_FREE(_PyUnicode_WSTR(unicode));
1731 _PyUnicode_WSTR(unicode) = NULL;
1732 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1733#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 }
1735 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1736 else {
1737#if SIZEOF_WCHAR_T == 2
1738 /* in case the native representation is 2-bytes, we need to allocate a
1739 new normalized 4-byte version. */
1740 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001741 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1742 PyErr_NoMemory();
1743 return -1;
1744 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001745 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1746 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 PyErr_NoMemory();
1748 return -1;
1749 }
1750 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1751 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001752 _PyUnicode_UTF8(unicode) = NULL;
1753 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001754 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1755 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001756 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 PyObject_FREE(_PyUnicode_WSTR(unicode));
1758 _PyUnicode_WSTR(unicode) = NULL;
1759 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1760#else
1761 assert(num_surrogates == 0);
1762
Victor Stinnerc3c74152011-10-02 20:39:55 +02001763 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001765 _PyUnicode_UTF8(unicode) = NULL;
1766 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1768#endif
1769 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1770 }
1771 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001772 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 return 0;
1774}
1775
Alexander Belopolsky40018472011-02-26 01:02:56 +00001776static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001777unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001778{
Walter Dörwald16807132007-05-25 13:52:07 +00001779 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001780 case SSTATE_NOT_INTERNED:
1781 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001782
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 case SSTATE_INTERNED_MORTAL:
1784 /* revive dead object temporarily for DelItem */
1785 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001786 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001787 Py_FatalError(
1788 "deletion of interned string failed");
1789 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001790
Benjamin Peterson29060642009-01-31 22:14:21 +00001791 case SSTATE_INTERNED_IMMORTAL:
1792 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001793 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001794
Benjamin Peterson29060642009-01-31 22:14:21 +00001795 default:
1796 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001797 }
1798
Victor Stinner03490912011-10-03 23:45:12 +02001799 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001801 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001802 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001803 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1804 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001806 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807}
1808
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001809#ifdef Py_DEBUG
1810static int
1811unicode_is_singleton(PyObject *unicode)
1812{
1813 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1814 if (unicode == unicode_empty)
1815 return 1;
1816 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1817 {
1818 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1819 if (ch < 256 && unicode_latin1[ch] == unicode)
1820 return 1;
1821 }
1822 return 0;
1823}
1824#endif
1825
Alexander Belopolsky40018472011-02-26 01:02:56 +00001826static int
Victor Stinner488fa492011-12-12 00:01:39 +01001827unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001828{
Victor Stinner488fa492011-12-12 00:01:39 +01001829 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001830 if (Py_REFCNT(unicode) != 1)
1831 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001832 if (_PyUnicode_HASH(unicode) != -1)
1833 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001834 if (PyUnicode_CHECK_INTERNED(unicode))
1835 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001836 if (!PyUnicode_CheckExact(unicode))
1837 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001838#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001839 /* singleton refcount is greater than 1 */
1840 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001841#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001842 return 1;
1843}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001844
Victor Stinnerfe226c02011-10-03 03:52:20 +02001845static int
1846unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1847{
1848 PyObject *unicode;
1849 Py_ssize_t old_length;
1850
1851 assert(p_unicode != NULL);
1852 unicode = *p_unicode;
1853
1854 assert(unicode != NULL);
1855 assert(PyUnicode_Check(unicode));
1856 assert(0 <= length);
1857
Victor Stinner910337b2011-10-03 03:20:16 +02001858 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001859 old_length = PyUnicode_WSTR_LENGTH(unicode);
1860 else
1861 old_length = PyUnicode_GET_LENGTH(unicode);
1862 if (old_length == length)
1863 return 0;
1864
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001865 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001866 _Py_INCREF_UNICODE_EMPTY();
1867 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001868 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001869 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001870 return 0;
1871 }
1872
Victor Stinner488fa492011-12-12 00:01:39 +01001873 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874 PyObject *copy = resize_copy(unicode, length);
1875 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001876 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001877 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001878 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001879 }
1880
Victor Stinnerfe226c02011-10-03 03:52:20 +02001881 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001882 PyObject *new_unicode = resize_compact(unicode, length);
1883 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001884 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001885 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001886 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001887 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001888 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001889}
1890
Alexander Belopolsky40018472011-02-26 01:02:56 +00001891int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001892PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001893{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001894 PyObject *unicode;
1895 if (p_unicode == NULL) {
1896 PyErr_BadInternalCall();
1897 return -1;
1898 }
1899 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001900 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001901 {
1902 PyErr_BadInternalCall();
1903 return -1;
1904 }
1905 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001906}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001907
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001908/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001909
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001910 WARNING: The function doesn't copy the terminating null character and
1911 doesn't check the maximum character (may write a latin1 character in an
1912 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001913static void
1914unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1915 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001916{
1917 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1918 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001919 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001920
1921 switch (kind) {
1922 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001923 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001924#ifdef Py_DEBUG
1925 if (PyUnicode_IS_ASCII(unicode)) {
1926 Py_UCS4 maxchar = ucs1lib_find_max_char(
1927 (const Py_UCS1*)str,
1928 (const Py_UCS1*)str + len);
1929 assert(maxchar < 128);
1930 }
1931#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001932 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001933 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001934 }
1935 case PyUnicode_2BYTE_KIND: {
1936 Py_UCS2 *start = (Py_UCS2 *)data + index;
1937 Py_UCS2 *ucs2 = start;
1938 assert(index <= PyUnicode_GET_LENGTH(unicode));
1939
Victor Stinner184252a2012-06-16 02:57:41 +02001940 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941 *ucs2 = (Py_UCS2)*str;
1942
1943 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001944 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001945 }
1946 default: {
1947 Py_UCS4 *start = (Py_UCS4 *)data + index;
1948 Py_UCS4 *ucs4 = start;
1949 assert(kind == PyUnicode_4BYTE_KIND);
1950 assert(index <= PyUnicode_GET_LENGTH(unicode));
1951
Victor Stinner184252a2012-06-16 02:57:41 +02001952 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001953 *ucs4 = (Py_UCS4)*str;
1954
1955 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001956 }
1957 }
1958}
1959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960static PyObject*
1961get_latin1_char(unsigned char ch)
1962{
Victor Stinnera464fc12011-10-02 20:39:30 +02001963 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001964 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001965 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001966 if (!unicode)
1967 return NULL;
1968 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001969 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001970 unicode_latin1[ch] = unicode;
1971 }
1972 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001973 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974}
1975
Victor Stinner985a82a2014-01-03 12:53:47 +01001976static PyObject*
1977unicode_char(Py_UCS4 ch)
1978{
1979 PyObject *unicode;
1980
1981 assert(ch <= MAX_UNICODE);
1982
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001983 if (ch < 256)
1984 return get_latin1_char(ch);
1985
Victor Stinner985a82a2014-01-03 12:53:47 +01001986 unicode = PyUnicode_New(1, ch);
1987 if (unicode == NULL)
1988 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001989
1990 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1991 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001992 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001993 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001994 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1995 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1996 }
1997 assert(_PyUnicode_CheckConsistency(unicode, 1));
1998 return unicode;
1999}
2000
Alexander Belopolsky40018472011-02-26 01:02:56 +00002001PyObject *
2002PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002003{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002004 if (u == NULL)
2005 return (PyObject*)_PyUnicode_New(size);
2006
2007 if (size < 0) {
2008 PyErr_BadInternalCall();
2009 return NULL;
2010 }
2011
2012 return PyUnicode_FromWideChar(u, size);
2013}
2014
2015PyObject *
2016PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2017{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002018 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 Py_UCS4 maxchar = 0;
2020 Py_ssize_t num_surrogates;
2021
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002022 if (u == NULL && size != 0) {
2023 PyErr_BadInternalCall();
2024 return NULL;
2025 }
2026
2027 if (size == -1) {
2028 size = wcslen(u);
2029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002030
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002031 /* If the Unicode data is known at construction time, we can apply
2032 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002035 if (size == 0)
2036 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038 /* Single character Unicode objects in the Latin-1 range are
2039 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002040 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 return get_latin1_char((unsigned char)*u);
2042
2043 /* If not empty and not single character, copy the Unicode data
2044 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002045 if (find_maxchar_surrogates(u, u + size,
2046 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return NULL;
2048
Victor Stinner8faf8212011-12-08 22:14:11 +01002049 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050 if (!unicode)
2051 return NULL;
2052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053 switch (PyUnicode_KIND(unicode)) {
2054 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002055 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2057 break;
2058 case PyUnicode_2BYTE_KIND:
2059#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002060 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002062 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2064#endif
2065 break;
2066 case PyUnicode_4BYTE_KIND:
2067#if SIZEOF_WCHAR_T == 2
2068 /* This is the only case which has to process surrogates, thus
2069 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002070 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071#else
2072 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002073 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074#endif
2075 break;
2076 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002077 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002079
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002080 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081}
2082
Alexander Belopolsky40018472011-02-26 01:02:56 +00002083PyObject *
2084PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002085{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002086 if (size < 0) {
2087 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002088 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002089 return NULL;
2090 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002091 if (u != NULL)
2092 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2093 else
2094 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002095}
2096
Alexander Belopolsky40018472011-02-26 01:02:56 +00002097PyObject *
2098PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002099{
2100 size_t size = strlen(u);
2101 if (size > PY_SSIZE_T_MAX) {
2102 PyErr_SetString(PyExc_OverflowError, "input too long");
2103 return NULL;
2104 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002105 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002106}
2107
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002108PyObject *
2109_PyUnicode_FromId(_Py_Identifier *id)
2110{
2111 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002112 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2113 strlen(id->string),
2114 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002115 if (!id->object)
2116 return NULL;
2117 PyUnicode_InternInPlace(&id->object);
2118 assert(!id->next);
2119 id->next = static_strings;
2120 static_strings = id;
2121 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002122 return id->object;
2123}
2124
2125void
2126_PyUnicode_ClearStaticStrings()
2127{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002128 _Py_Identifier *tmp, *s = static_strings;
2129 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002130 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002131 tmp = s->next;
2132 s->next = NULL;
2133 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002134 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002135 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002136}
2137
Benjamin Peterson0df54292012-03-26 14:50:32 -04002138/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002139
Victor Stinnerd3f08822012-05-29 12:57:52 +02002140PyObject*
2141_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002142{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002143 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002144 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002145 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002146#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002147 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002148#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002149 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002150 }
Victor Stinner785938e2011-12-11 20:09:03 +01002151 unicode = PyUnicode_New(size, 127);
2152 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002153 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002154 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2155 assert(_PyUnicode_CheckConsistency(unicode, 1));
2156 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002157}
2158
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002159static Py_UCS4
2160kind_maxchar_limit(unsigned int kind)
2161{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002162 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002163 case PyUnicode_1BYTE_KIND:
2164 return 0x80;
2165 case PyUnicode_2BYTE_KIND:
2166 return 0x100;
2167 case PyUnicode_4BYTE_KIND:
2168 return 0x10000;
2169 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002170 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002171 }
2172}
2173
Victor Stinner702c7342011-10-05 13:50:52 +02002174static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002175_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002178 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002179
Serhiy Storchaka678db842013-01-26 12:16:36 +02002180 if (size == 0)
2181 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002182 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002183 if (size == 1)
2184 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002185
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002186 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002187 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002188 if (!res)
2189 return NULL;
2190 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002191 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002193}
2194
Victor Stinnere57b1c02011-09-28 22:20:48 +02002195static PyObject*
2196_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197{
2198 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002199 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002200
Serhiy Storchaka678db842013-01-26 12:16:36 +02002201 if (size == 0)
2202 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002203 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002204 if (size == 1)
2205 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002207 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002208 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 if (!res)
2210 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002211 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002213 else {
2214 _PyUnicode_CONVERT_BYTES(
2215 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2216 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002217 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return res;
2219}
2220
Victor Stinnere57b1c02011-09-28 22:20:48 +02002221static PyObject*
2222_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223{
2224 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002225 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002226
Serhiy Storchaka678db842013-01-26 12:16:36 +02002227 if (size == 0)
2228 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002229 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002230 if (size == 1)
2231 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002232
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002233 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002234 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002235 if (!res)
2236 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002237 if (max_char < 256)
2238 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2239 PyUnicode_1BYTE_DATA(res));
2240 else if (max_char < 0x10000)
2241 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2242 PyUnicode_2BYTE_DATA(res));
2243 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002244 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002245 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 return res;
2247}
2248
2249PyObject*
2250PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2251{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002252 if (size < 0) {
2253 PyErr_SetString(PyExc_ValueError, "size must be positive");
2254 return NULL;
2255 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002256 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002258 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002260 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002262 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002263 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002264 PyErr_SetString(PyExc_SystemError, "invalid kind");
2265 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267}
2268
Victor Stinnerece58de2012-04-23 23:36:38 +02002269Py_UCS4
2270_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2271{
2272 enum PyUnicode_Kind kind;
2273 void *startptr, *endptr;
2274
2275 assert(PyUnicode_IS_READY(unicode));
2276 assert(0 <= start);
2277 assert(end <= PyUnicode_GET_LENGTH(unicode));
2278 assert(start <= end);
2279
2280 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2281 return PyUnicode_MAX_CHAR_VALUE(unicode);
2282
2283 if (start == end)
2284 return 127;
2285
Victor Stinner94d558b2012-04-27 22:26:58 +02002286 if (PyUnicode_IS_ASCII(unicode))
2287 return 127;
2288
Victor Stinnerece58de2012-04-23 23:36:38 +02002289 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002290 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002291 endptr = (char *)startptr + end * kind;
2292 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002293 switch(kind) {
2294 case PyUnicode_1BYTE_KIND:
2295 return ucs1lib_find_max_char(startptr, endptr);
2296 case PyUnicode_2BYTE_KIND:
2297 return ucs2lib_find_max_char(startptr, endptr);
2298 case PyUnicode_4BYTE_KIND:
2299 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002300 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002301 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002302 }
2303}
2304
Victor Stinner25a4b292011-10-06 12:31:55 +02002305/* Ensure that a string uses the most efficient storage, if it is not the
2306 case: create a new string with of the right kind. Write NULL into *p_unicode
2307 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002308static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002309unicode_adjust_maxchar(PyObject **p_unicode)
2310{
2311 PyObject *unicode, *copy;
2312 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002313 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002314 unsigned int kind;
2315
2316 assert(p_unicode != NULL);
2317 unicode = *p_unicode;
2318 assert(PyUnicode_IS_READY(unicode));
2319 if (PyUnicode_IS_ASCII(unicode))
2320 return;
2321
2322 len = PyUnicode_GET_LENGTH(unicode);
2323 kind = PyUnicode_KIND(unicode);
2324 if (kind == PyUnicode_1BYTE_KIND) {
2325 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002326 max_char = ucs1lib_find_max_char(u, u + len);
2327 if (max_char >= 128)
2328 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002329 }
2330 else if (kind == PyUnicode_2BYTE_KIND) {
2331 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002332 max_char = ucs2lib_find_max_char(u, u + len);
2333 if (max_char >= 256)
2334 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002335 }
2336 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002337 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002338 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002339 max_char = ucs4lib_find_max_char(u, u + len);
2340 if (max_char >= 0x10000)
2341 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002342 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002343 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002344 if (copy != NULL)
2345 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002346 Py_DECREF(unicode);
2347 *p_unicode = copy;
2348}
2349
Victor Stinner034f6cf2011-09-30 02:26:44 +02002350PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002351_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002352{
Victor Stinner87af4f22011-11-21 23:03:47 +01002353 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002354 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002355
Victor Stinner034f6cf2011-09-30 02:26:44 +02002356 if (!PyUnicode_Check(unicode)) {
2357 PyErr_BadInternalCall();
2358 return NULL;
2359 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002360 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002361 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002362
Victor Stinner87af4f22011-11-21 23:03:47 +01002363 length = PyUnicode_GET_LENGTH(unicode);
2364 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002365 if (!copy)
2366 return NULL;
2367 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2368
Christian Heimesf051e432016-09-13 20:22:02 +02002369 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002370 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002371 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002372 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002373}
2374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375
Victor Stinnerbc603d12011-10-02 01:00:40 +02002376/* Widen Unicode objects to larger buffers. Don't write terminating null
2377 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002378
2379void*
2380_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2381{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002382 Py_ssize_t len;
2383 void *result;
2384 unsigned int skind;
2385
Benjamin Petersonbac79492012-01-14 13:34:47 -05002386 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002387 return NULL;
2388
2389 len = PyUnicode_GET_LENGTH(s);
2390 skind = PyUnicode_KIND(s);
2391 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002392 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 return NULL;
2394 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002395 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002396 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002397 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002398 if (!result)
2399 return PyErr_NoMemory();
2400 assert(skind == PyUnicode_1BYTE_KIND);
2401 _PyUnicode_CONVERT_BYTES(
2402 Py_UCS1, Py_UCS2,
2403 PyUnicode_1BYTE_DATA(s),
2404 PyUnicode_1BYTE_DATA(s) + len,
2405 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002407 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002408 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 if (!result)
2410 return PyErr_NoMemory();
2411 if (skind == PyUnicode_2BYTE_KIND) {
2412 _PyUnicode_CONVERT_BYTES(
2413 Py_UCS2, Py_UCS4,
2414 PyUnicode_2BYTE_DATA(s),
2415 PyUnicode_2BYTE_DATA(s) + len,
2416 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002418 else {
2419 assert(skind == PyUnicode_1BYTE_KIND);
2420 _PyUnicode_CONVERT_BYTES(
2421 Py_UCS1, Py_UCS4,
2422 PyUnicode_1BYTE_DATA(s),
2423 PyUnicode_1BYTE_DATA(s) + len,
2424 result);
2425 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002427 default:
2428 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 }
Victor Stinner01698042011-10-04 00:04:26 +02002430 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 return NULL;
2432}
2433
2434static Py_UCS4*
2435as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2436 int copy_null)
2437{
2438 int kind;
2439 void *data;
2440 Py_ssize_t len, targetlen;
2441 if (PyUnicode_READY(string) == -1)
2442 return NULL;
2443 kind = PyUnicode_KIND(string);
2444 data = PyUnicode_DATA(string);
2445 len = PyUnicode_GET_LENGTH(string);
2446 targetlen = len;
2447 if (copy_null)
2448 targetlen++;
2449 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002450 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 if (!target) {
2452 PyErr_NoMemory();
2453 return NULL;
2454 }
2455 }
2456 else {
2457 if (targetsize < targetlen) {
2458 PyErr_Format(PyExc_SystemError,
2459 "string is longer than the buffer");
2460 if (copy_null && 0 < targetsize)
2461 target[0] = 0;
2462 return NULL;
2463 }
2464 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002465 if (kind == PyUnicode_1BYTE_KIND) {
2466 Py_UCS1 *start = (Py_UCS1 *) data;
2467 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002469 else if (kind == PyUnicode_2BYTE_KIND) {
2470 Py_UCS2 *start = (Py_UCS2 *) data;
2471 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2472 }
2473 else {
2474 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002475 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 if (copy_null)
2478 target[len] = 0;
2479 return target;
2480}
2481
2482Py_UCS4*
2483PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2484 int copy_null)
2485{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002486 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 PyErr_BadInternalCall();
2488 return NULL;
2489 }
2490 return as_ucs4(string, target, targetsize, copy_null);
2491}
2492
2493Py_UCS4*
2494PyUnicode_AsUCS4Copy(PyObject *string)
2495{
2496 return as_ucs4(string, NULL, 0, 1);
2497}
2498
Victor Stinner15a11362012-10-06 23:48:20 +02002499/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002500 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2501 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2502#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002503
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002504static int
2505unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2506 Py_ssize_t width, Py_ssize_t precision)
2507{
2508 Py_ssize_t length, fill, arglen;
2509 Py_UCS4 maxchar;
2510
2511 if (PyUnicode_READY(str) == -1)
2512 return -1;
2513
2514 length = PyUnicode_GET_LENGTH(str);
2515 if ((precision == -1 || precision >= length)
2516 && width <= length)
2517 return _PyUnicodeWriter_WriteStr(writer, str);
2518
2519 if (precision != -1)
2520 length = Py_MIN(precision, length);
2521
2522 arglen = Py_MAX(length, width);
2523 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2524 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2525 else
2526 maxchar = writer->maxchar;
2527
2528 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2529 return -1;
2530
2531 if (width > length) {
2532 fill = width - length;
2533 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2534 return -1;
2535 writer->pos += fill;
2536 }
2537
2538 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2539 str, 0, length);
2540 writer->pos += length;
2541 return 0;
2542}
2543
2544static int
2545unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2546 Py_ssize_t width, Py_ssize_t precision)
2547{
2548 /* UTF-8 */
2549 Py_ssize_t length;
2550 PyObject *unicode;
2551 int res;
2552
2553 length = strlen(str);
2554 if (precision != -1)
2555 length = Py_MIN(length, precision);
2556 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2557 if (unicode == NULL)
2558 return -1;
2559
2560 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2561 Py_DECREF(unicode);
2562 return res;
2563}
2564
Victor Stinner96865452011-03-01 23:44:09 +00002565static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002566unicode_fromformat_arg(_PyUnicodeWriter *writer,
2567 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002568{
Victor Stinnere215d962012-10-06 23:03:36 +02002569 const char *p;
2570 Py_ssize_t len;
2571 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002572 Py_ssize_t width;
2573 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002574 int longflag;
2575 int longlongflag;
2576 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002577 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002578
2579 p = f;
2580 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002581 zeropad = 0;
2582 if (*f == '0') {
2583 zeropad = 1;
2584 f++;
2585 }
Victor Stinner96865452011-03-01 23:44:09 +00002586
2587 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002588 width = -1;
2589 if (Py_ISDIGIT((unsigned)*f)) {
2590 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002591 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002592 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002593 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002594 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002596 return NULL;
2597 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002599 f++;
2600 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002601 }
2602 precision = -1;
2603 if (*f == '.') {
2604 f++;
2605 if (Py_ISDIGIT((unsigned)*f)) {
2606 precision = (*f - '0');
2607 f++;
2608 while (Py_ISDIGIT((unsigned)*f)) {
2609 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2610 PyErr_SetString(PyExc_ValueError,
2611 "precision too big");
2612 return NULL;
2613 }
2614 precision = (precision * 10) + (*f - '0');
2615 f++;
2616 }
2617 }
Victor Stinner96865452011-03-01 23:44:09 +00002618 if (*f == '%') {
2619 /* "%.3%s" => f points to "3" */
2620 f--;
2621 }
2622 }
2623 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002624 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002625 f--;
2626 }
Victor Stinner96865452011-03-01 23:44:09 +00002627
2628 /* Handle %ld, %lu, %lld and %llu. */
2629 longflag = 0;
2630 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002631 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002632 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002633 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002634 longflag = 1;
2635 ++f;
2636 }
Victor Stinner96865452011-03-01 23:44:09 +00002637 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002638 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002639 longlongflag = 1;
2640 f += 2;
2641 }
Victor Stinner96865452011-03-01 23:44:09 +00002642 }
2643 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002644 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002645 size_tflag = 1;
2646 ++f;
2647 }
Victor Stinnere215d962012-10-06 23:03:36 +02002648
2649 if (f[1] == '\0')
2650 writer->overallocate = 0;
2651
2652 switch (*f) {
2653 case 'c':
2654 {
2655 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002656 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002657 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002658 "character argument not in range(0x110000)");
2659 return NULL;
2660 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002661 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002662 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002663 break;
2664 }
2665
2666 case 'i':
2667 case 'd':
2668 case 'u':
2669 case 'x':
2670 {
2671 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002672 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002673 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002674
2675 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002676 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002677 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002678 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002679 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002680 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002681 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002682 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002683 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002684 va_arg(*vargs, size_t));
2685 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002686 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002687 va_arg(*vargs, unsigned int));
2688 }
2689 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002690 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002691 }
2692 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002693 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002694 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002695 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002696 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002697 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002698 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002699 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002700 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002701 va_arg(*vargs, Py_ssize_t));
2702 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002703 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002704 va_arg(*vargs, int));
2705 }
2706 assert(len >= 0);
2707
Victor Stinnere215d962012-10-06 23:03:36 +02002708 if (precision < len)
2709 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002710
2711 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2713 return NULL;
2714
Victor Stinnere215d962012-10-06 23:03:36 +02002715 if (width > precision) {
2716 Py_UCS4 fillchar;
2717 fill = width - precision;
2718 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002719 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2720 return NULL;
2721 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002722 }
Victor Stinner15a11362012-10-06 23:48:20 +02002723 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002724 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002725 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2726 return NULL;
2727 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002728 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002729
Victor Stinner4a587072013-11-19 12:54:53 +01002730 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2731 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002732 break;
2733 }
2734
2735 case 'p':
2736 {
2737 char number[MAX_LONG_LONG_CHARS];
2738
2739 len = sprintf(number, "%p", va_arg(*vargs, void*));
2740 assert(len >= 0);
2741
2742 /* %p is ill-defined: ensure leading 0x. */
2743 if (number[1] == 'X')
2744 number[1] = 'x';
2745 else if (number[1] != 'x') {
2746 memmove(number + 2, number,
2747 strlen(number) + 1);
2748 number[0] = '0';
2749 number[1] = 'x';
2750 len += 2;
2751 }
2752
Victor Stinner4a587072013-11-19 12:54:53 +01002753 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002754 return NULL;
2755 break;
2756 }
2757
2758 case 's':
2759 {
2760 /* UTF-8 */
2761 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002762 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002763 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002764 break;
2765 }
2766
2767 case 'U':
2768 {
2769 PyObject *obj = va_arg(*vargs, PyObject *);
2770 assert(obj && _PyUnicode_CHECK(obj));
2771
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002772 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002773 return NULL;
2774 break;
2775 }
2776
2777 case 'V':
2778 {
2779 PyObject *obj = va_arg(*vargs, PyObject *);
2780 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002781 if (obj) {
2782 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002783 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002784 return NULL;
2785 }
2786 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002787 assert(str != NULL);
2788 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002789 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002790 }
2791 break;
2792 }
2793
2794 case 'S':
2795 {
2796 PyObject *obj = va_arg(*vargs, PyObject *);
2797 PyObject *str;
2798 assert(obj);
2799 str = PyObject_Str(obj);
2800 if (!str)
2801 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002802 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002803 Py_DECREF(str);
2804 return NULL;
2805 }
2806 Py_DECREF(str);
2807 break;
2808 }
2809
2810 case 'R':
2811 {
2812 PyObject *obj = va_arg(*vargs, PyObject *);
2813 PyObject *repr;
2814 assert(obj);
2815 repr = PyObject_Repr(obj);
2816 if (!repr)
2817 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002818 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002819 Py_DECREF(repr);
2820 return NULL;
2821 }
2822 Py_DECREF(repr);
2823 break;
2824 }
2825
2826 case 'A':
2827 {
2828 PyObject *obj = va_arg(*vargs, PyObject *);
2829 PyObject *ascii;
2830 assert(obj);
2831 ascii = PyObject_ASCII(obj);
2832 if (!ascii)
2833 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002834 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002835 Py_DECREF(ascii);
2836 return NULL;
2837 }
2838 Py_DECREF(ascii);
2839 break;
2840 }
2841
2842 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002843 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002844 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002845 break;
2846
2847 default:
2848 /* if we stumble upon an unknown formatting code, copy the rest
2849 of the format string to the output string. (we cannot just
2850 skip the code, since there's no way to know what's in the
2851 argument list) */
2852 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002853 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002854 return NULL;
2855 f = p+len;
2856 return f;
2857 }
2858
2859 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002860 return f;
2861}
2862
Walter Dörwaldd2034312007-05-18 16:29:38 +00002863PyObject *
2864PyUnicode_FromFormatV(const char *format, va_list vargs)
2865{
Victor Stinnere215d962012-10-06 23:03:36 +02002866 va_list vargs2;
2867 const char *f;
2868 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002869
Victor Stinner8f674cc2013-04-17 23:02:17 +02002870 _PyUnicodeWriter_Init(&writer);
2871 writer.min_length = strlen(format) + 100;
2872 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002873
Benjamin Peterson0c212142016-09-20 20:39:33 -07002874 // Copy varags to be able to pass a reference to a subfunction.
2875 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002876
2877 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002878 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002879 f = unicode_fromformat_arg(&writer, f, &vargs2);
2880 if (f == NULL)
2881 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002883 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002884 const char *p;
2885 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002886
Victor Stinnere215d962012-10-06 23:03:36 +02002887 p = f;
2888 do
2889 {
2890 if ((unsigned char)*p > 127) {
2891 PyErr_Format(PyExc_ValueError,
2892 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2893 "string, got a non-ASCII byte: 0x%02x",
2894 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002895 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002896 }
2897 p++;
2898 }
2899 while (*p != '\0' && *p != '%');
2900 len = p - f;
2901
2902 if (*p == '\0')
2903 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002904
2905 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002906 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002907
2908 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002909 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002910 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002911 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002912 return _PyUnicodeWriter_Finish(&writer);
2913
2914 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002915 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002916 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918}
2919
Walter Dörwaldd2034312007-05-18 16:29:38 +00002920PyObject *
2921PyUnicode_FromFormat(const char *format, ...)
2922{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002923 PyObject* ret;
2924 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925
2926#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002927 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002928#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002929 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002930#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002931 ret = PyUnicode_FromFormatV(format, vargs);
2932 va_end(vargs);
2933 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002934}
2935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002936#ifdef HAVE_WCHAR_H
2937
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002938/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00002939
Victor Stinnerd88d9832011-09-06 02:00:05 +02002940 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002941 character) required to convert the unicode object. Ignore size argument.
2942
Victor Stinnerd88d9832011-09-06 02:00:05 +02002943 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002944 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002945 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002946Py_ssize_t
2947PyUnicode_AsWideChar(PyObject *unicode,
2948 wchar_t *w,
2949 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00002950{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002951 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 const wchar_t *wstr;
2953
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002954 if (unicode == NULL) {
2955 PyErr_BadInternalCall();
2956 return -1;
2957 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002958 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (wstr == NULL)
2960 return -1;
2961
Victor Stinner5593d8a2010-10-02 11:11:27 +00002962 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002963 if (size > res)
2964 size = res + 1;
2965 else
2966 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002967 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002968 return res;
2969 }
2970 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002971 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002972}
2973
Victor Stinner137c34c2010-09-29 10:25:54 +00002974wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002975PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002976 Py_ssize_t *size)
2977{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002978 const wchar_t *wstr;
2979 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00002980 Py_ssize_t buflen;
2981
2982 if (unicode == NULL) {
2983 PyErr_BadInternalCall();
2984 return NULL;
2985 }
2986
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002987 wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen);
2988 if (wstr == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002989 return NULL;
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002990 }
2991 if (size == NULL && wcslen(wstr) != (size_t)buflen) {
2992 PyErr_SetString(PyExc_ValueError,
2993 "embedded null character");
2994 return NULL;
2995 }
2996
2997 buffer = PyMem_NEW(wchar_t, buflen + 1);
Victor Stinner137c34c2010-09-29 10:25:54 +00002998 if (buffer == NULL) {
2999 PyErr_NoMemory();
3000 return NULL;
3001 }
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003002 memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00003003 if (size != NULL)
3004 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003005 return buffer;
3006}
3007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003008#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003009
Alexander Belopolsky40018472011-02-26 01:02:56 +00003010PyObject *
3011PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003012{
Victor Stinner8faf8212011-12-08 22:14:11 +01003013 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003014 PyErr_SetString(PyExc_ValueError,
3015 "chr() arg not in range(0x110000)");
3016 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003017 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003018
Victor Stinner985a82a2014-01-03 12:53:47 +01003019 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003020}
3021
Alexander Belopolsky40018472011-02-26 01:02:56 +00003022PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003023PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003024{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003025 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003027 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003028 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003029 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003030 Py_INCREF(obj);
3031 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003032 }
3033 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 /* For a Unicode subtype that's not a Unicode object,
3035 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003036 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003037 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003038 PyErr_Format(PyExc_TypeError,
3039 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003040 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003041 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003042}
3043
Alexander Belopolsky40018472011-02-26 01:02:56 +00003044PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003045PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003046 const char *encoding,
3047 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003048{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003049 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003050 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003051
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 PyErr_BadInternalCall();
3054 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003055 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 /* Decoding bytes objects is the most common case and should be fast */
3058 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003059 if (PyBytes_GET_SIZE(obj) == 0)
3060 _Py_RETURN_UNICODE_EMPTY();
3061 v = PyUnicode_Decode(
3062 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3063 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003064 return v;
3065 }
3066
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003067 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 PyErr_SetString(PyExc_TypeError,
3069 "decoding str is not supported");
3070 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003071 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003072
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003073 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3074 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3075 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003076 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003077 Py_TYPE(obj)->tp_name);
3078 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003079 }
Tim Petersced69f82003-09-16 20:30:58 +00003080
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003081 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003082 PyBuffer_Release(&buffer);
3083 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003084 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003085
Serhiy Storchaka05997252013-01-26 12:14:02 +02003086 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003087 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003088 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089}
3090
Victor Stinnerebe17e02016-10-12 13:57:45 +02003091/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3092 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3093 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003094int
3095_Py_normalize_encoding(const char *encoding,
3096 char *lower,
3097 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003098{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003099 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003100 char *l;
3101 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003102 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003103
Victor Stinner942889a2016-09-05 15:40:10 -07003104 assert(encoding != NULL);
3105
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003106 e = encoding;
3107 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003108 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003109 punct = 0;
3110 while (1) {
3111 char c = *e;
3112 if (c == 0) {
3113 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003114 }
Victor Stinner942889a2016-09-05 15:40:10 -07003115
3116 if (Py_ISALNUM(c) || c == '.') {
3117 if (punct && l != lower) {
3118 if (l == l_end) {
3119 return 0;
3120 }
3121 *l++ = '_';
3122 }
3123 punct = 0;
3124
3125 if (l == l_end) {
3126 return 0;
3127 }
3128 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003129 }
3130 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003131 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003132 }
Victor Stinner942889a2016-09-05 15:40:10 -07003133
3134 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003135 }
3136 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003137 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003138}
3139
Alexander Belopolsky40018472011-02-26 01:02:56 +00003140PyObject *
3141PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003142 Py_ssize_t size,
3143 const char *encoding,
3144 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003145{
3146 PyObject *buffer = NULL, *unicode;
3147 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003148 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3149
3150 if (encoding == NULL) {
3151 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3152 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003153
Fred Drakee4315f52000-05-09 19:53:39 +00003154 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003155 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3156 char *lower = buflower;
3157
3158 /* Fast paths */
3159 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3160 lower += 3;
3161 if (*lower == '_') {
3162 /* Match "utf8" and "utf_8" */
3163 lower++;
3164 }
3165
3166 if (lower[0] == '8' && lower[1] == 0) {
3167 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3168 }
3169 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3170 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3171 }
3172 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3173 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3174 }
3175 }
3176 else {
3177 if (strcmp(lower, "ascii") == 0
3178 || strcmp(lower, "us_ascii") == 0) {
3179 return PyUnicode_DecodeASCII(s, size, errors);
3180 }
Steve Dowercc16be82016-09-08 10:35:16 -07003181 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003182 else if (strcmp(lower, "mbcs") == 0) {
3183 return PyUnicode_DecodeMBCS(s, size, errors);
3184 }
3185 #endif
3186 else if (strcmp(lower, "latin1") == 0
3187 || strcmp(lower, "latin_1") == 0
3188 || strcmp(lower, "iso_8859_1") == 0
3189 || strcmp(lower, "iso8859_1") == 0) {
3190 return PyUnicode_DecodeLatin1(s, size, errors);
3191 }
3192 }
Victor Stinner37296e82010-06-10 13:36:23 +00003193 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003194
3195 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003196 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003197 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003198 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003199 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200 if (buffer == NULL)
3201 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003202 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203 if (unicode == NULL)
3204 goto onError;
3205 if (!PyUnicode_Check(unicode)) {
3206 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003207 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3208 "use codecs.decode() to decode to arbitrary types",
3209 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003210 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003211 Py_DECREF(unicode);
3212 goto onError;
3213 }
3214 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003215 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003216
Benjamin Peterson29060642009-01-31 22:14:21 +00003217 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003218 Py_XDECREF(buffer);
3219 return NULL;
3220}
3221
Alexander Belopolsky40018472011-02-26 01:02:56 +00003222PyObject *
3223PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003224 const char *encoding,
3225 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003226{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003227 if (!PyUnicode_Check(unicode)) {
3228 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003229 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003230 }
3231
Serhiy Storchaka00939072016-10-27 21:05:49 +03003232 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3233 "PyUnicode_AsDecodedObject() is deprecated; "
3234 "use PyCodec_Decode() to decode from str", 1) < 0)
3235 return NULL;
3236
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003237 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003239
3240 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003241 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242}
3243
Alexander Belopolsky40018472011-02-26 01:02:56 +00003244PyObject *
3245PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003246 const char *encoding,
3247 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003248{
3249 PyObject *v;
3250
3251 if (!PyUnicode_Check(unicode)) {
3252 PyErr_BadArgument();
3253 goto onError;
3254 }
3255
Serhiy Storchaka00939072016-10-27 21:05:49 +03003256 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3257 "PyUnicode_AsDecodedUnicode() is deprecated; "
3258 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3259 return NULL;
3260
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003261 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003262 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003263
3264 /* Decode via the codec registry */
3265 v = PyCodec_Decode(unicode, encoding, errors);
3266 if (v == NULL)
3267 goto onError;
3268 if (!PyUnicode_Check(v)) {
3269 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003270 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3271 "use codecs.decode() to decode to arbitrary types",
3272 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003273 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003274 Py_DECREF(v);
3275 goto onError;
3276 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003277 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003278
Benjamin Peterson29060642009-01-31 22:14:21 +00003279 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003280 return NULL;
3281}
3282
Alexander Belopolsky40018472011-02-26 01:02:56 +00003283PyObject *
3284PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003285 Py_ssize_t size,
3286 const char *encoding,
3287 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003288{
3289 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003290
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003291 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003294 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3295 Py_DECREF(unicode);
3296 return v;
3297}
3298
Alexander Belopolsky40018472011-02-26 01:02:56 +00003299PyObject *
3300PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003301 const char *encoding,
3302 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003303{
3304 PyObject *v;
3305
3306 if (!PyUnicode_Check(unicode)) {
3307 PyErr_BadArgument();
3308 goto onError;
3309 }
3310
Serhiy Storchaka00939072016-10-27 21:05:49 +03003311 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3312 "PyUnicode_AsEncodedObject() is deprecated; "
3313 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3314 "or PyCodec_Encode() for generic encoding", 1) < 0)
3315 return NULL;
3316
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003317 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003318 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003319
3320 /* Encode via the codec registry */
3321 v = PyCodec_Encode(unicode, encoding, errors);
3322 if (v == NULL)
3323 goto onError;
3324 return v;
3325
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003327 return NULL;
3328}
3329
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003330static size_t
3331wcstombs_errorpos(const wchar_t *wstr)
3332{
3333 size_t len;
3334#if SIZEOF_WCHAR_T == 2
3335 wchar_t buf[3];
3336#else
3337 wchar_t buf[2];
3338#endif
3339 char outbuf[MB_LEN_MAX];
3340 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003341
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003342#if SIZEOF_WCHAR_T == 2
3343 buf[2] = 0;
3344#else
3345 buf[1] = 0;
3346#endif
3347 start = wstr;
3348 while (*wstr != L'\0')
3349 {
3350 previous = wstr;
3351#if SIZEOF_WCHAR_T == 2
3352 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3353 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3354 {
3355 buf[0] = wstr[0];
3356 buf[1] = wstr[1];
3357 wstr += 2;
3358 }
3359 else {
3360 buf[0] = *wstr;
3361 buf[1] = 0;
3362 wstr++;
3363 }
3364#else
3365 buf[0] = *wstr;
3366 wstr++;
3367#endif
3368 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003369 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003370 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003371 }
3372
3373 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003374 return 0;
3375}
3376
Victor Stinner1b579672011-12-17 05:47:23 +01003377static int
3378locale_error_handler(const char *errors, int *surrogateescape)
3379{
Victor Stinner50149202015-09-22 00:26:54 +02003380 _Py_error_handler error_handler = get_error_handler(errors);
3381 switch (error_handler)
3382 {
3383 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003384 *surrogateescape = 0;
3385 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003386 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003387 *surrogateescape = 1;
3388 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003389 default:
3390 PyErr_Format(PyExc_ValueError,
3391 "only 'strict' and 'surrogateescape' error handlers "
3392 "are supported, not '%s'",
3393 errors);
3394 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003395 }
Victor Stinner1b579672011-12-17 05:47:23 +01003396}
3397
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003399PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003400{
3401 Py_ssize_t wlen, wlen2;
3402 wchar_t *wstr;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003403 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003404 PyObject *bytes, *reason, *exc;
3405 size_t error_pos, errlen;
Victor Stinner1b579672011-12-17 05:47:23 +01003406 int surrogateescape;
3407
3408 if (locale_error_handler(errors, &surrogateescape) < 0)
3409 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410
3411 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3412 if (wstr == NULL)
3413 return NULL;
3414
3415 wlen2 = wcslen(wstr);
3416 if (wlen2 != wlen) {
3417 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003418 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003419 return NULL;
3420 }
3421
3422 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003423 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003424 char *str;
3425
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003426 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 if (str == NULL) {
3428 if (error_pos == (size_t)-1) {
3429 PyErr_NoMemory();
3430 PyMem_Free(wstr);
3431 return NULL;
3432 }
3433 else {
3434 goto encode_error;
3435 }
3436 }
3437 PyMem_Free(wstr);
3438
3439 bytes = PyBytes_FromString(str);
3440 PyMem_Free(str);
3441 }
3442 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003443 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003444 size_t len, len2;
3445
3446 len = wcstombs(NULL, wstr, 0);
3447 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003448 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003449 goto encode_error;
3450 }
3451
3452 bytes = PyBytes_FromStringAndSize(NULL, len);
3453 if (bytes == NULL) {
3454 PyMem_Free(wstr);
3455 return NULL;
3456 }
3457
3458 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3459 if (len2 == (size_t)-1 || len2 > len) {
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003460 Py_DECREF(bytes);
Victor Stinner2f197072011-12-17 07:08:30 +01003461 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003462 goto encode_error;
3463 }
3464 PyMem_Free(wstr);
3465 }
3466 return bytes;
3467
3468encode_error:
3469 errmsg = strerror(errno);
3470 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003471
3472 if (error_pos == (size_t)-1)
3473 error_pos = wcstombs_errorpos(wstr);
3474
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003475 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003476
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003477 wstr = Py_DecodeLocale(errmsg, &errlen);
3478 if (wstr != NULL) {
3479 reason = PyUnicode_FromWideChar(wstr, errlen);
3480 PyMem_RawFree(wstr);
3481 } else {
3482 errmsg = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003483 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003484
Victor Stinner2f197072011-12-17 07:08:30 +01003485 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003486 reason = PyUnicode_FromString(
3487 "wcstombs() encountered an unencodable "
3488 "wide character");
3489 if (reason == NULL)
3490 return NULL;
3491
3492 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3493 "locale", unicode,
3494 (Py_ssize_t)error_pos,
3495 (Py_ssize_t)(error_pos+1),
3496 reason);
3497 Py_DECREF(reason);
3498 if (exc != NULL) {
3499 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003500 Py_DECREF(exc);
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003501 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003502 return NULL;
3503}
3504
Victor Stinnerad158722010-10-27 00:25:46 +00003505PyObject *
3506PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003507{
Steve Dowercc16be82016-09-08 10:35:16 -07003508#if defined(__APPLE__)
3509 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003510#else
Victor Stinner793b5312011-04-27 00:24:21 +02003511 PyInterpreterState *interp = PyThreadState_GET()->interp;
3512 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3513 cannot use it to encode and decode filenames before it is loaded. Load
3514 the Python codec requires to encode at least its own filename. Use the C
3515 version of the locale codec until the codec registry is initialized and
3516 the Python codec is loaded.
3517
3518 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3519 cannot only rely on it: check also interp->fscodec_initialized for
3520 subinterpreters. */
3521 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003522 return PyUnicode_AsEncodedString(unicode,
3523 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003524 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003525 }
3526 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003527 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003528 }
Victor Stinnerad158722010-10-27 00:25:46 +00003529#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003530}
3531
Alexander Belopolsky40018472011-02-26 01:02:56 +00003532PyObject *
3533PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003534 const char *encoding,
3535 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003536{
3537 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003538 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003539
Guido van Rossumd57fd912000-03-10 22:53:23 +00003540 if (!PyUnicode_Check(unicode)) {
3541 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543 }
Fred Drakee4315f52000-05-09 19:53:39 +00003544
Victor Stinner942889a2016-09-05 15:40:10 -07003545 if (encoding == NULL) {
3546 return _PyUnicode_AsUTF8String(unicode, errors);
3547 }
3548
Fred Drakee4315f52000-05-09 19:53:39 +00003549 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003550 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3551 char *lower = buflower;
3552
3553 /* Fast paths */
3554 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3555 lower += 3;
3556 if (*lower == '_') {
3557 /* Match "utf8" and "utf_8" */
3558 lower++;
3559 }
3560
3561 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003562 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003563 }
3564 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3565 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3566 }
3567 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3568 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3569 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003570 }
Victor Stinner942889a2016-09-05 15:40:10 -07003571 else {
3572 if (strcmp(lower, "ascii") == 0
3573 || strcmp(lower, "us_ascii") == 0) {
3574 return _PyUnicode_AsASCIIString(unicode, errors);
3575 }
Steve Dowercc16be82016-09-08 10:35:16 -07003576#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003577 else if (strcmp(lower, "mbcs") == 0) {
3578 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3579 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003580#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003581 else if (strcmp(lower, "latin1") == 0 ||
3582 strcmp(lower, "latin_1") == 0 ||
3583 strcmp(lower, "iso_8859_1") == 0 ||
3584 strcmp(lower, "iso8859_1") == 0) {
3585 return _PyUnicode_AsLatin1String(unicode, errors);
3586 }
3587 }
Victor Stinner37296e82010-06-10 13:36:23 +00003588 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003589
3590 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003591 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003592 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003593 return NULL;
3594
3595 /* The normal path */
3596 if (PyBytes_Check(v))
3597 return v;
3598
3599 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003600 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003601 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003602 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003603
3604 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003605 "encoder %s returned bytearray instead of bytes; "
3606 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003607 encoding);
3608 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003609 Py_DECREF(v);
3610 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003611 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003612
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003613 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3614 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003615 Py_DECREF(v);
3616 return b;
3617 }
3618
3619 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003620 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3621 "use codecs.encode() to encode to arbitrary types",
3622 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003623 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003624 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003625 return NULL;
3626}
3627
Alexander Belopolsky40018472011-02-26 01:02:56 +00003628PyObject *
3629PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003630 const char *encoding,
3631 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003632{
3633 PyObject *v;
3634
3635 if (!PyUnicode_Check(unicode)) {
3636 PyErr_BadArgument();
3637 goto onError;
3638 }
3639
Serhiy Storchaka00939072016-10-27 21:05:49 +03003640 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3641 "PyUnicode_AsEncodedUnicode() is deprecated; "
3642 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3643 return NULL;
3644
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003645 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003646 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003647
3648 /* Encode via the codec registry */
3649 v = PyCodec_Encode(unicode, encoding, errors);
3650 if (v == NULL)
3651 goto onError;
3652 if (!PyUnicode_Check(v)) {
3653 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003654 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3655 "use codecs.encode() to encode to arbitrary types",
3656 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003657 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003658 Py_DECREF(v);
3659 goto onError;
3660 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003661 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003662
Benjamin Peterson29060642009-01-31 22:14:21 +00003663 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003664 return NULL;
3665}
3666
Victor Stinner2f197072011-12-17 07:08:30 +01003667static size_t
3668mbstowcs_errorpos(const char *str, size_t len)
3669{
3670#ifdef HAVE_MBRTOWC
3671 const char *start = str;
3672 mbstate_t mbs;
3673 size_t converted;
3674 wchar_t ch;
3675
3676 memset(&mbs, 0, sizeof mbs);
3677 while (len)
3678 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003679 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003680 if (converted == 0)
3681 /* Reached end of string */
3682 break;
3683 if (converted == (size_t)-1 || converted == (size_t)-2) {
3684 /* Conversion error or incomplete character */
3685 return str - start;
3686 }
3687 else {
3688 str += converted;
3689 len -= converted;
3690 }
3691 }
3692 /* failed to find the undecodable byte sequence */
3693 return 0;
3694#endif
3695 return 0;
3696}
3697
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003698PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003699PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003700 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003701{
3702 wchar_t smallbuf[256];
3703 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3704 wchar_t *wstr;
3705 size_t wlen, wlen2;
3706 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003707 int surrogateescape;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003708 size_t error_pos, errlen;
Victor Stinner2f197072011-12-17 07:08:30 +01003709 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003710 PyObject *exc, *reason = NULL; /* initialize to prevent gcc warning */
Victor Stinner1b579672011-12-17 05:47:23 +01003711
3712 if (locale_error_handler(errors, &surrogateescape) < 0)
3713 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003714
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003715 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3716 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003717 return NULL;
3718 }
3719
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003720 if (surrogateescape) {
3721 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003722 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003723 if (wstr == NULL) {
3724 if (wlen == (size_t)-1)
3725 PyErr_NoMemory();
3726 else
3727 PyErr_SetFromErrno(PyExc_OSError);
3728 return NULL;
3729 }
3730
3731 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003732 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003733 }
3734 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003735 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003736#ifndef HAVE_BROKEN_MBSTOWCS
3737 wlen = mbstowcs(NULL, str, 0);
3738#else
3739 wlen = len;
3740#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003741 if (wlen == (size_t)-1)
3742 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003743 if (wlen+1 <= smallbuf_len) {
3744 wstr = smallbuf;
3745 }
3746 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003747 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003748 if (!wstr)
3749 return PyErr_NoMemory();
3750 }
3751
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003752 wlen2 = mbstowcs(wstr, str, wlen+1);
3753 if (wlen2 == (size_t)-1) {
3754 if (wstr != smallbuf)
3755 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003756 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003757 }
3758#ifdef HAVE_BROKEN_MBSTOWCS
3759 assert(wlen2 == wlen);
3760#endif
3761 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3762 if (wstr != smallbuf)
3763 PyMem_Free(wstr);
3764 }
3765 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003766
3767decode_error:
3768 errmsg = strerror(errno);
3769 assert(errmsg != NULL);
3770
3771 error_pos = mbstowcs_errorpos(str, len);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003772 wstr = Py_DecodeLocale(errmsg, &errlen);
3773 if (wstr != NULL) {
3774 reason = PyUnicode_FromWideChar(wstr, errlen);
3775 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003776 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003777
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003778 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003779 reason = PyUnicode_FromString(
3780 "mbstowcs() encountered an invalid multibyte sequence");
3781 if (reason == NULL)
3782 return NULL;
3783
3784 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3785 "locale", str, len,
3786 (Py_ssize_t)error_pos,
3787 (Py_ssize_t)(error_pos+1),
3788 reason);
3789 Py_DECREF(reason);
3790 if (exc != NULL) {
3791 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003792 Py_DECREF(exc);
Victor Stinner2f197072011-12-17 07:08:30 +01003793 }
3794 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003795}
3796
3797PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003798PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003799{
3800 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003801 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003802}
3803
3804
3805PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003806PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003807 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003808 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3809}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003810
Christian Heimes5894ba72007-11-04 11:43:14 +00003811PyObject*
3812PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3813{
Steve Dowercc16be82016-09-08 10:35:16 -07003814#if defined(__APPLE__)
3815 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003816#else
Victor Stinner793b5312011-04-27 00:24:21 +02003817 PyInterpreterState *interp = PyThreadState_GET()->interp;
3818 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3819 cannot use it to encode and decode filenames before it is loaded. Load
3820 the Python codec requires to encode at least its own filename. Use the C
3821 version of the locale codec until the codec registry is initialized and
3822 the Python codec is loaded.
3823
3824 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3825 cannot only rely on it: check also interp->fscodec_initialized for
3826 subinterpreters. */
3827 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003828 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003829 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003830 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003831 }
3832 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003833 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003834 }
Victor Stinnerad158722010-10-27 00:25:46 +00003835#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003836}
3837
Martin v. Löwis011e8422009-05-05 04:43:17 +00003838
3839int
3840PyUnicode_FSConverter(PyObject* arg, void* addr)
3841{
Brett Cannonec6ce872016-09-06 15:50:29 -07003842 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003843 PyObject *output = NULL;
3844 Py_ssize_t size;
3845 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003846 if (arg == NULL) {
3847 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003848 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003849 return 1;
3850 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003851 path = PyOS_FSPath(arg);
3852 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003853 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003854 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003855 if (PyBytes_Check(path)) {
3856 output = path;
3857 }
3858 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3859 output = PyUnicode_EncodeFSDefault(path);
3860 Py_DECREF(path);
3861 if (!output) {
3862 return 0;
3863 }
3864 assert(PyBytes_Check(output));
3865 }
3866
Victor Stinner0ea2a462010-04-30 00:22:08 +00003867 size = PyBytes_GET_SIZE(output);
3868 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003869 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003870 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003871 Py_DECREF(output);
3872 return 0;
3873 }
3874 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003875 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003876}
3877
3878
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003879int
3880PyUnicode_FSDecoder(PyObject* arg, void* addr)
3881{
Brett Cannona5711202016-09-06 19:36:01 -07003882 int is_buffer = 0;
3883 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003884 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003885 if (arg == NULL) {
3886 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003887 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003888 return 1;
3889 }
Brett Cannona5711202016-09-06 19:36:01 -07003890
3891 is_buffer = PyObject_CheckBuffer(arg);
3892 if (!is_buffer) {
3893 path = PyOS_FSPath(arg);
3894 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003895 return 0;
3896 }
Brett Cannona5711202016-09-06 19:36:01 -07003897 }
3898 else {
3899 path = arg;
3900 Py_INCREF(arg);
3901 }
3902
3903 if (PyUnicode_Check(path)) {
3904 if (PyUnicode_READY(path) == -1) {
3905 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003906 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003907 }
3908 output = path;
3909 }
3910 else if (PyBytes_Check(path) || is_buffer) {
3911 PyObject *path_bytes = NULL;
3912
3913 if (!PyBytes_Check(path) &&
3914 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3915 "path should be string, bytes, or os.PathLike, not %.200s",
3916 Py_TYPE(arg)->tp_name)) {
3917 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003918 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003919 }
3920 path_bytes = PyBytes_FromObject(path);
3921 Py_DECREF(path);
3922 if (!path_bytes) {
3923 return 0;
3924 }
3925 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3926 PyBytes_GET_SIZE(path_bytes));
3927 Py_DECREF(path_bytes);
3928 if (!output) {
3929 return 0;
3930 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003931 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003932 else {
3933 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003934 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003935 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003936 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003937 return 0;
3938 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003939 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003940 Py_DECREF(output);
3941 return 0;
3942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003944 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003945 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003946 Py_DECREF(output);
3947 return 0;
3948 }
3949 *(PyObject**)addr = output;
3950 return Py_CLEANUP_SUPPORTED;
3951}
3952
3953
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003954const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003955PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003956{
Christian Heimesf3863112007-11-22 07:46:41 +00003957 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003958
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003959 if (!PyUnicode_Check(unicode)) {
3960 PyErr_BadArgument();
3961 return NULL;
3962 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003963 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003964 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003965
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003966 if (PyUnicode_UTF8(unicode) == NULL) {
3967 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003968 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003969 if (bytes == NULL)
3970 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003971 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3972 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003973 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 Py_DECREF(bytes);
3975 return NULL;
3976 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003977 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003978 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003979 PyBytes_AS_STRING(bytes),
3980 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981 Py_DECREF(bytes);
3982 }
3983
3984 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003985 *psize = PyUnicode_UTF8_LENGTH(unicode);
3986 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003987}
3988
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003989const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003990PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003991{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3993}
3994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003995Py_UNICODE *
3996PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3997{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 const unsigned char *one_byte;
3999#if SIZEOF_WCHAR_T == 4
4000 const Py_UCS2 *two_bytes;
4001#else
4002 const Py_UCS4 *four_bytes;
4003 const Py_UCS4 *ucs4_end;
4004 Py_ssize_t num_surrogates;
4005#endif
4006 wchar_t *w;
4007 wchar_t *wchar_end;
4008
4009 if (!PyUnicode_Check(unicode)) {
4010 PyErr_BadArgument();
4011 return NULL;
4012 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004013 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004014 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004015 assert(_PyUnicode_KIND(unicode) != 0);
4016 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004017
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004018 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004020 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4021 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022 num_surrogates = 0;
4023
4024 for (; four_bytes < ucs4_end; ++four_bytes) {
4025 if (*four_bytes > 0xFFFF)
4026 ++num_surrogates;
4027 }
4028
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004029 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4030 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4031 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004032 PyErr_NoMemory();
4033 return NULL;
4034 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004035 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004036
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004037 w = _PyUnicode_WSTR(unicode);
4038 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4039 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004040 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4041 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004042 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004043 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004044 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4045 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004046 }
4047 else
4048 *w = *four_bytes;
4049
4050 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07004051 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004052 }
4053 }
4054 *w = 0;
4055#else
4056 /* sizeof(wchar_t) == 4 */
4057 Py_FatalError("Impossible unicode object state, wstr and str "
4058 "should share memory already.");
4059 return NULL;
4060#endif
4061 }
4062 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004063 if ((size_t)_PyUnicode_LENGTH(unicode) >
4064 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4065 PyErr_NoMemory();
4066 return NULL;
4067 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004068 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4069 (_PyUnicode_LENGTH(unicode) + 1));
4070 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004071 PyErr_NoMemory();
4072 return NULL;
4073 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004074 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4075 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4076 w = _PyUnicode_WSTR(unicode);
4077 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004078
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004079 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4080 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004081 for (; w < wchar_end; ++one_byte, ++w)
4082 *w = *one_byte;
4083 /* null-terminate the wstr */
4084 *w = 0;
4085 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004086 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004088 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004089 for (; w < wchar_end; ++two_bytes, ++w)
4090 *w = *two_bytes;
4091 /* null-terminate the wstr */
4092 *w = 0;
4093#else
4094 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004095 PyObject_FREE(_PyUnicode_WSTR(unicode));
4096 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097 Py_FatalError("Impossible unicode object state, wstr "
4098 "and str should share memory already.");
4099 return NULL;
4100#endif
4101 }
4102 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07004103 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004104 }
4105 }
4106 }
4107 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004108 *size = PyUnicode_WSTR_LENGTH(unicode);
4109 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004110}
4111
Alexander Belopolsky40018472011-02-26 01:02:56 +00004112Py_UNICODE *
4113PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004114{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004115 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004116}
4117
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03004118const Py_UNICODE *
4119_PyUnicode_AsUnicode(PyObject *unicode)
4120{
4121 Py_ssize_t size;
4122 const Py_UNICODE *wstr;
4123
4124 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
4125 if (wstr && wcslen(wstr) != (size_t)size) {
4126 PyErr_SetString(PyExc_ValueError, "embedded null character");
4127 return NULL;
4128 }
4129 return wstr;
4130}
4131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004132
Alexander Belopolsky40018472011-02-26 01:02:56 +00004133Py_ssize_t
4134PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004135{
4136 if (!PyUnicode_Check(unicode)) {
4137 PyErr_BadArgument();
4138 goto onError;
4139 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004140 if (_PyUnicode_WSTR(unicode) == NULL) {
4141 if (PyUnicode_AsUnicode(unicode) == NULL)
4142 goto onError;
4143 }
4144 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004145
Benjamin Peterson29060642009-01-31 22:14:21 +00004146 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004147 return -1;
4148}
4149
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004150Py_ssize_t
4151PyUnicode_GetLength(PyObject *unicode)
4152{
Victor Stinner07621332012-06-16 04:53:46 +02004153 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004154 PyErr_BadArgument();
4155 return -1;
4156 }
Victor Stinner07621332012-06-16 04:53:46 +02004157 if (PyUnicode_READY(unicode) == -1)
4158 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004159 return PyUnicode_GET_LENGTH(unicode);
4160}
4161
4162Py_UCS4
4163PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4164{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004165 void *data;
4166 int kind;
4167
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004168 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004169 PyErr_BadArgument();
4170 return (Py_UCS4)-1;
4171 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004172 if (PyUnicode_READY(unicode) == -1) {
4173 return (Py_UCS4)-1;
4174 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004175 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004176 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004177 return (Py_UCS4)-1;
4178 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004179 data = PyUnicode_DATA(unicode);
4180 kind = PyUnicode_KIND(unicode);
4181 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004182}
4183
4184int
4185PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4186{
4187 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004188 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004189 return -1;
4190 }
Victor Stinner488fa492011-12-12 00:01:39 +01004191 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004192 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004193 PyErr_SetString(PyExc_IndexError, "string index out of range");
4194 return -1;
4195 }
Victor Stinner488fa492011-12-12 00:01:39 +01004196 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004197 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004198 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4199 PyErr_SetString(PyExc_ValueError, "character out of range");
4200 return -1;
4201 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004202 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4203 index, ch);
4204 return 0;
4205}
4206
Alexander Belopolsky40018472011-02-26 01:02:56 +00004207const char *
4208PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004209{
Victor Stinner42cb4622010-09-01 19:39:01 +00004210 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004211}
4212
Victor Stinner554f3f02010-06-16 23:33:54 +00004213/* create or adjust a UnicodeDecodeError */
4214static void
4215make_decode_exception(PyObject **exceptionObject,
4216 const char *encoding,
4217 const char *input, Py_ssize_t length,
4218 Py_ssize_t startpos, Py_ssize_t endpos,
4219 const char *reason)
4220{
4221 if (*exceptionObject == NULL) {
4222 *exceptionObject = PyUnicodeDecodeError_Create(
4223 encoding, input, length, startpos, endpos, reason);
4224 }
4225 else {
4226 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4227 goto onError;
4228 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4229 goto onError;
4230 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4231 goto onError;
4232 }
4233 return;
4234
4235onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004236 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004237}
4238
Steve Dowercc16be82016-09-08 10:35:16 -07004239#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004240/* error handling callback helper:
4241 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004242 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004243 and adjust various state variables.
4244 return 0 on success, -1 on error
4245*/
4246
Alexander Belopolsky40018472011-02-26 01:02:56 +00004247static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004248unicode_decode_call_errorhandler_wchar(
4249 const char *errors, PyObject **errorHandler,
4250 const char *encoding, const char *reason,
4251 const char **input, const char **inend, Py_ssize_t *startinpos,
4252 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4253 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004254{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004255 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004256
4257 PyObject *restuple = NULL;
4258 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004259 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004260 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004261 Py_ssize_t requiredsize;
4262 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004263 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004264 wchar_t *repwstr;
4265 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004267 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4268 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004269
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004270 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 *errorHandler = PyCodec_LookupError(errors);
4272 if (*errorHandler == NULL)
4273 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004274 }
4275
Victor Stinner554f3f02010-06-16 23:33:54 +00004276 make_decode_exception(exceptionObject,
4277 encoding,
4278 *input, *inend - *input,
4279 *startinpos, *endinpos,
4280 reason);
4281 if (*exceptionObject == NULL)
4282 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004283
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004284 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004285 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004286 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004287 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004288 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004289 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004290 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004291 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004292 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004293
4294 /* Copy back the bytes variables, which might have been modified by the
4295 callback */
4296 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4297 if (!inputobj)
4298 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004299 *input = PyBytes_AS_STRING(inputobj);
4300 insize = PyBytes_GET_SIZE(inputobj);
4301 *inend = *input + insize;
4302 /* we can DECREF safely, as the exception has another reference,
4303 so the object won't go away. */
4304 Py_DECREF(inputobj);
4305
4306 if (newpos<0)
4307 newpos = insize+newpos;
4308 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004309 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004310 goto onError;
4311 }
4312
4313 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4314 if (repwstr == NULL)
4315 goto onError;
4316 /* need more space? (at least enough for what we
4317 have+the replacement+the rest of the string (starting
4318 at the new input position), so we won't have to check space
4319 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004320 requiredsize = *outpos;
4321 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4322 goto overflow;
4323 requiredsize += repwlen;
4324 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4325 goto overflow;
4326 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004327 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004328 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004329 requiredsize = 2*outsize;
4330 if (unicode_resize(output, requiredsize) < 0)
4331 goto onError;
4332 }
4333 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4334 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004335 *endinpos = newpos;
4336 *inptr = *input + newpos;
4337
4338 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004339 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004340 return 0;
4341
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004342 overflow:
4343 PyErr_SetString(PyExc_OverflowError,
4344 "decoded result is too long for a Python string");
4345
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004346 onError:
4347 Py_XDECREF(restuple);
4348 return -1;
4349}
Steve Dowercc16be82016-09-08 10:35:16 -07004350#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004351
4352static int
4353unicode_decode_call_errorhandler_writer(
4354 const char *errors, PyObject **errorHandler,
4355 const char *encoding, const char *reason,
4356 const char **input, const char **inend, Py_ssize_t *startinpos,
4357 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4358 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4359{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004360 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004361
4362 PyObject *restuple = NULL;
4363 PyObject *repunicode = NULL;
4364 Py_ssize_t insize;
4365 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004366 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004367 PyObject *inputobj = NULL;
4368
4369 if (*errorHandler == NULL) {
4370 *errorHandler = PyCodec_LookupError(errors);
4371 if (*errorHandler == NULL)
4372 goto onError;
4373 }
4374
4375 make_decode_exception(exceptionObject,
4376 encoding,
4377 *input, *inend - *input,
4378 *startinpos, *endinpos,
4379 reason);
4380 if (*exceptionObject == NULL)
4381 goto onError;
4382
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004383 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004384 if (restuple == NULL)
4385 goto onError;
4386 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004387 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004388 goto onError;
4389 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004390 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004391 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004392
4393 /* Copy back the bytes variables, which might have been modified by the
4394 callback */
4395 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4396 if (!inputobj)
4397 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004398 *input = PyBytes_AS_STRING(inputobj);
4399 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004400 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004401 /* we can DECREF safely, as the exception has another reference,
4402 so the object won't go away. */
4403 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004405 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004406 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004407 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004408 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004409 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004410 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004411
Victor Stinner170ca6f2013-04-18 00:25:28 +02004412 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004413 if (replen > 1) {
4414 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004415 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004416 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4417 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4418 goto onError;
4419 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004421 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004422
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004423 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004424 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004425
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004426 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004427 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004428 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004429
Benjamin Peterson29060642009-01-31 22:14:21 +00004430 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004433}
4434
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435/* --- UTF-7 Codec -------------------------------------------------------- */
4436
Antoine Pitrou244651a2009-05-04 18:56:13 +00004437/* See RFC2152 for details. We encode conservatively and decode liberally. */
4438
4439/* Three simple macros defining base-64. */
4440
4441/* Is c a base-64 character? */
4442
4443#define IS_BASE64(c) \
4444 (((c) >= 'A' && (c) <= 'Z') || \
4445 ((c) >= 'a' && (c) <= 'z') || \
4446 ((c) >= '0' && (c) <= '9') || \
4447 (c) == '+' || (c) == '/')
4448
4449/* given that c is a base-64 character, what is its base-64 value? */
4450
4451#define FROM_BASE64(c) \
4452 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4453 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4454 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4455 (c) == '+' ? 62 : 63)
4456
4457/* What is the base-64 character of the bottom 6 bits of n? */
4458
4459#define TO_BASE64(n) \
4460 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4461
4462/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4463 * decoded as itself. We are permissive on decoding; the only ASCII
4464 * byte not decoding to itself is the + which begins a base64
4465 * string. */
4466
4467#define DECODE_DIRECT(c) \
4468 ((c) <= 127 && (c) != '+')
4469
4470/* The UTF-7 encoder treats ASCII characters differently according to
4471 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4472 * the above). See RFC2152. This array identifies these different
4473 * sets:
4474 * 0 : "Set D"
4475 * alphanumeric and '(),-./:?
4476 * 1 : "Set O"
4477 * !"#$%&*;<=>@[]^_`{|}
4478 * 2 : "whitespace"
4479 * ht nl cr sp
4480 * 3 : special (must be base64 encoded)
4481 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4482 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483
Tim Petersced69f82003-09-16 20:30:58 +00004484static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004485char utf7_category[128] = {
4486/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4487 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4488/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4489 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4490/* sp ! " # $ % & ' ( ) * + , - . / */
4491 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4492/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4493 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4494/* @ A B C D E F G H I J K L M N O */
4495 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4496/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4497 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4498/* ` a b c d e f g h i j k l m n o */
4499 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4500/* p q r s t u v w x y z { | } ~ del */
4501 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502};
4503
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504/* ENCODE_DIRECT: this character should be encoded as itself. The
4505 * answer depends on whether we are encoding set O as itself, and also
4506 * on whether we are encoding whitespace as itself. RFC2152 makes it
4507 * clear that the answers to these questions vary between
4508 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004509
Antoine Pitrou244651a2009-05-04 18:56:13 +00004510#define ENCODE_DIRECT(c, directO, directWS) \
4511 ((c) < 128 && (c) > 0 && \
4512 ((utf7_category[(c)] == 0) || \
4513 (directWS && (utf7_category[(c)] == 2)) || \
4514 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515
Alexander Belopolsky40018472011-02-26 01:02:56 +00004516PyObject *
4517PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004518 Py_ssize_t size,
4519 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004521 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4522}
4523
Antoine Pitrou244651a2009-05-04 18:56:13 +00004524/* The decoder. The only state we preserve is our read position,
4525 * i.e. how many characters we have consumed. So if we end in the
4526 * middle of a shift sequence we have to back off the read position
4527 * and the output to the beginning of the sequence, otherwise we lose
4528 * all the shift state (seen bits, number of bits seen, high
4529 * surrogate). */
4530
Alexander Belopolsky40018472011-02-26 01:02:56 +00004531PyObject *
4532PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004533 Py_ssize_t size,
4534 const char *errors,
4535 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004536{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004537 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004538 Py_ssize_t startinpos;
4539 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004541 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 const char *errmsg = "";
4543 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004544 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 unsigned int base64bits = 0;
4546 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004547 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004548 PyObject *errorHandler = NULL;
4549 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004551 if (size == 0) {
4552 if (consumed)
4553 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004554 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004555 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004557 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004558 _PyUnicodeWriter_Init(&writer);
4559 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004560
4561 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004562 e = s + size;
4563
4564 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004565 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004566 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004567 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004568
Antoine Pitrou244651a2009-05-04 18:56:13 +00004569 if (inShift) { /* in a base-64 section */
4570 if (IS_BASE64(ch)) { /* consume a base-64 character */
4571 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4572 base64bits += 6;
4573 s++;
4574 if (base64bits >= 16) {
4575 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004576 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 base64bits -= 16;
4578 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004579 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 if (surrogate) {
4581 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004582 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4583 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004584 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004585 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004587 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004588 }
4589 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004590 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004591 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004592 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 }
4594 }
Victor Stinner551ac952011-11-29 22:58:13 +01004595 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 /* first surrogate */
4597 surrogate = outCh;
4598 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004600 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004601 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 }
4603 }
4604 }
4605 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004606 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004607 if (base64bits > 0) { /* left-over bits */
4608 if (base64bits >= 6) {
4609 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004610 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004611 errmsg = "partial character in shift sequence";
4612 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004614 else {
4615 /* Some bits remain; they should be zero */
4616 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004617 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004618 errmsg = "non-zero padding bits in shift sequence";
4619 goto utf7Error;
4620 }
4621 }
4622 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004623 if (surrogate && DECODE_DIRECT(ch)) {
4624 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4625 goto onError;
4626 }
4627 surrogate = 0;
4628 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004629 /* '-' is absorbed; other terminating
4630 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004631 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004632 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004633 }
4634 }
4635 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004636 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004637 s++; /* consume '+' */
4638 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004639 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004640 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004641 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004642 }
4643 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004644 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004645 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004646 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004647 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004648 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004649 }
4650 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004651 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004652 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004653 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004654 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004655 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004656 else {
4657 startinpos = s-starts;
4658 s++;
4659 errmsg = "unexpected special character";
4660 goto utf7Error;
4661 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004662 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004663utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004664 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004665 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004666 errors, &errorHandler,
4667 "utf7", errmsg,
4668 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004669 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004670 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004671 }
4672
Antoine Pitrou244651a2009-05-04 18:56:13 +00004673 /* end of string */
4674
4675 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4676 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004677 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004678 if (surrogate ||
4679 (base64bits >= 6) ||
4680 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004681 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004682 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004683 errors, &errorHandler,
4684 "utf7", "unterminated shift sequence",
4685 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004686 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004687 goto onError;
4688 if (s < e)
4689 goto restart;
4690 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004691 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004692
4693 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004694 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004695 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004696 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004697 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004698 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004699 writer.kind, writer.data, shiftOutStart);
4700 Py_XDECREF(errorHandler);
4701 Py_XDECREF(exc);
4702 _PyUnicodeWriter_Dealloc(&writer);
4703 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004704 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004705 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004706 }
4707 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004708 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004709 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004710 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004711
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004712 Py_XDECREF(errorHandler);
4713 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004714 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004715
Benjamin Peterson29060642009-01-31 22:14:21 +00004716 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004717 Py_XDECREF(errorHandler);
4718 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004719 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004720 return NULL;
4721}
4722
4723
Alexander Belopolsky40018472011-02-26 01:02:56 +00004724PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004725_PyUnicode_EncodeUTF7(PyObject *str,
4726 int base64SetO,
4727 int base64WhiteSpace,
4728 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004729{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004730 int kind;
4731 void *data;
4732 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004733 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004735 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004736 unsigned int base64bits = 0;
4737 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004738 char * out;
4739 char * start;
4740
Benjamin Petersonbac79492012-01-14 13:34:47 -05004741 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004742 return NULL;
4743 kind = PyUnicode_KIND(str);
4744 data = PyUnicode_DATA(str);
4745 len = PyUnicode_GET_LENGTH(str);
4746
4747 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004748 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004749
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004750 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004751 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004752 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004753 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004754 if (v == NULL)
4755 return NULL;
4756
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004757 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004758 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004759 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004760
Antoine Pitrou244651a2009-05-04 18:56:13 +00004761 if (inShift) {
4762 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4763 /* shifting out */
4764 if (base64bits) { /* output remaining bits */
4765 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4766 base64buffer = 0;
4767 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768 }
4769 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004770 /* Characters not in the BASE64 set implicitly unshift the sequence
4771 so no '-' is required, except if the character is itself a '-' */
4772 if (IS_BASE64(ch) || ch == '-') {
4773 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004774 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004775 *out++ = (char) ch;
4776 }
4777 else {
4778 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004779 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004780 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004781 else { /* not in a shift sequence */
4782 if (ch == '+') {
4783 *out++ = '+';
4784 *out++ = '-';
4785 }
4786 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4787 *out++ = (char) ch;
4788 }
4789 else {
4790 *out++ = '+';
4791 inShift = 1;
4792 goto encode_char;
4793 }
4794 }
4795 continue;
4796encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004797 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004798 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004799
Antoine Pitrou244651a2009-05-04 18:56:13 +00004800 /* code first surrogate */
4801 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004802 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004803 while (base64bits >= 6) {
4804 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4805 base64bits -= 6;
4806 }
4807 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004808 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004809 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004810 base64bits += 16;
4811 base64buffer = (base64buffer << 16) | ch;
4812 while (base64bits >= 6) {
4813 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4814 base64bits -= 6;
4815 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004816 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004817 if (base64bits)
4818 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4819 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004820 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004821 if (_PyBytes_Resize(&v, out - start) < 0)
4822 return NULL;
4823 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004824}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004825PyObject *
4826PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4827 Py_ssize_t size,
4828 int base64SetO,
4829 int base64WhiteSpace,
4830 const char *errors)
4831{
4832 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004833 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004834 if (tmp == NULL)
4835 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004836 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004837 base64WhiteSpace, errors);
4838 Py_DECREF(tmp);
4839 return result;
4840}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004841
Antoine Pitrou244651a2009-05-04 18:56:13 +00004842#undef IS_BASE64
4843#undef FROM_BASE64
4844#undef TO_BASE64
4845#undef DECODE_DIRECT
4846#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004847
Guido van Rossumd57fd912000-03-10 22:53:23 +00004848/* --- UTF-8 Codec -------------------------------------------------------- */
4849
Alexander Belopolsky40018472011-02-26 01:02:56 +00004850PyObject *
4851PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004852 Py_ssize_t size,
4853 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004854{
Walter Dörwald69652032004-09-07 20:24:22 +00004855 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4856}
4857
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004858#include "stringlib/asciilib.h"
4859#include "stringlib/codecs.h"
4860#include "stringlib/undef.h"
4861
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004862#include "stringlib/ucs1lib.h"
4863#include "stringlib/codecs.h"
4864#include "stringlib/undef.h"
4865
4866#include "stringlib/ucs2lib.h"
4867#include "stringlib/codecs.h"
4868#include "stringlib/undef.h"
4869
4870#include "stringlib/ucs4lib.h"
4871#include "stringlib/codecs.h"
4872#include "stringlib/undef.h"
4873
Antoine Pitrouab868312009-01-10 15:40:25 +00004874/* Mask to quickly check whether a C 'long' contains a
4875 non-ASCII, UTF8-encoded char. */
4876#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004877# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004878#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004879# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004880#else
4881# error C 'long' size should be either 4 or 8!
4882#endif
4883
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004884static Py_ssize_t
4885ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004886{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004887 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004888 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004889
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004890 /*
4891 * Issue #17237: m68k is a bit different from most architectures in
4892 * that objects do not use "natural alignment" - for example, int and
4893 * long are only aligned at 2-byte boundaries. Therefore the assert()
4894 * won't work; also, tests have shown that skipping the "optimised
4895 * version" will even speed up m68k.
4896 */
4897#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004898#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004899 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4900 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004901 /* Fast path, see in STRINGLIB(utf8_decode) for
4902 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004903 /* Help allocation */
4904 const char *_p = p;
4905 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004906 while (_p < aligned_end) {
4907 unsigned long value = *(const unsigned long *) _p;
4908 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004909 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910 *((unsigned long *)q) = value;
4911 _p += SIZEOF_LONG;
4912 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004913 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004914 p = _p;
4915 while (p < end) {
4916 if ((unsigned char)*p & 0x80)
4917 break;
4918 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004919 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004920 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004921 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004922#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004923#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004924 while (p < end) {
4925 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4926 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004927 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004928 /* Help allocation */
4929 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004930 while (_p < aligned_end) {
4931 unsigned long value = *(unsigned long *) _p;
4932 if (value & ASCII_CHAR_MASK)
4933 break;
4934 _p += SIZEOF_LONG;
4935 }
4936 p = _p;
4937 if (_p == end)
4938 break;
4939 }
4940 if ((unsigned char)*p & 0x80)
4941 break;
4942 ++p;
4943 }
4944 memcpy(dest, start, p - start);
4945 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004946}
Antoine Pitrouab868312009-01-10 15:40:25 +00004947
Victor Stinner785938e2011-12-11 20:09:03 +01004948PyObject *
4949PyUnicode_DecodeUTF8Stateful(const char *s,
4950 Py_ssize_t size,
4951 const char *errors,
4952 Py_ssize_t *consumed)
4953{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004954 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004955 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004957
4958 Py_ssize_t startinpos;
4959 Py_ssize_t endinpos;
4960 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004961 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004963 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004964
4965 if (size == 0) {
4966 if (consumed)
4967 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004968 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004969 }
4970
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004971 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4972 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004973 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 *consumed = 1;
4975 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004976 }
4977
Victor Stinner8f674cc2013-04-17 23:02:17 +02004978 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004979 writer.min_length = size;
4980 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004982
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004983 writer.pos = ascii_decode(s, end, writer.data);
4984 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004985 while (s < end) {
4986 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004987 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004988
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004989 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004990 if (PyUnicode_IS_ASCII(writer.buffer))
4991 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004992 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004993 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004994 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004995 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 } else {
4997 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004998 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004999 }
5000
5001 switch (ch) {
5002 case 0:
5003 if (s == end || consumed)
5004 goto End;
5005 errmsg = "unexpected end of data";
5006 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005007 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 break;
5009 case 1:
5010 errmsg = "invalid start byte";
5011 startinpos = s - starts;
5012 endinpos = startinpos + 1;
5013 break;
5014 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005015 case 3:
5016 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005017 errmsg = "invalid continuation byte";
5018 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005019 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005020 break;
5021 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005022 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005023 goto onError;
5024 continue;
5025 }
5026
Victor Stinner1d65d912015-10-05 13:43:50 +02005027 if (error_handler == _Py_ERROR_UNKNOWN)
5028 error_handler = get_error_handler(errors);
5029
5030 switch (error_handler) {
5031 case _Py_ERROR_IGNORE:
5032 s += (endinpos - startinpos);
5033 break;
5034
5035 case _Py_ERROR_REPLACE:
5036 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5037 goto onError;
5038 s += (endinpos - startinpos);
5039 break;
5040
5041 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005042 {
5043 Py_ssize_t i;
5044
Victor Stinner1d65d912015-10-05 13:43:50 +02005045 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5046 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005047 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005048 ch = (Py_UCS4)(unsigned char)(starts[i]);
5049 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5050 ch + 0xdc00);
5051 writer.pos++;
5052 }
5053 s += (endinpos - startinpos);
5054 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005055 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005056
5057 default:
5058 if (unicode_decode_call_errorhandler_writer(
5059 errors, &error_handler_obj,
5060 "utf-8", errmsg,
5061 &starts, &end, &startinpos, &endinpos, &exc, &s,
5062 &writer))
5063 goto onError;
5064 }
Victor Stinner785938e2011-12-11 20:09:03 +01005065 }
5066
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005067End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005068 if (consumed)
5069 *consumed = s - starts;
5070
Victor Stinner1d65d912015-10-05 13:43:50 +02005071 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005072 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005073 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005074
5075onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005076 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005077 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005078 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005079 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005080}
5081
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005082
Victor Stinner91106cd2017-12-13 12:29:09 +01005083/* UTF-8 decoder using the surrogateescape error handler .
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005084
Victor Stinner91106cd2017-12-13 12:29:09 +01005085 On success, return a pointer to a newly allocated wide character string (use
5086 PyMem_RawFree() to free the memory) and write the output length (in number
5087 of wchar_t units) into *p_wlen (if p_wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005088
Victor Stinner91106cd2017-12-13 12:29:09 +01005089 On memory allocation failure, return -1 and write (size_t)-1 into *p_wlen
5090 (if p_wlen is set). */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005091wchar_t*
Victor Stinner91106cd2017-12-13 12:29:09 +01005092_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size, size_t *p_wlen)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005093{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005094 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005095 wchar_t *unicode;
5096 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005097
5098 /* Note: size will always be longer than the resulting Unicode
5099 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01005100 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
5101 if (p_wlen) {
5102 *p_wlen = (size_t)-1;
5103 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005104 return NULL;
Victor Stinner91106cd2017-12-13 12:29:09 +01005105 }
5106
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005107 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01005108 if (!unicode) {
5109 if (p_wlen) {
5110 *p_wlen = (size_t)-1;
5111 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005112 return NULL;
Victor Stinner91106cd2017-12-13 12:29:09 +01005113 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005114
5115 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005116 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005117 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005118 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005119 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005120#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005121 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005122#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005123 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005124#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005125 if (ch > 0xFF) {
5126#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005127 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005128#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005129 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005130 /* compute and append the two surrogates: */
5131 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5132 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5133#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005134 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005135 else {
5136 if (!ch && s == e)
5137 break;
5138 /* surrogateescape */
5139 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5140 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005141 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005142 unicode[outpos] = L'\0';
Victor Stinner91106cd2017-12-13 12:29:09 +01005143 if (p_wlen) {
5144 *p_wlen = outpos;
5145 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005146 return unicode;
5147}
5148
Antoine Pitrouab868312009-01-10 15:40:25 +00005149
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005150/* Primary internal function which creates utf8 encoded bytes objects.
5151
5152 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005153 and allocate exactly as much space needed at the end. Else allocate the
5154 maximum possible needed (4 result bytes per Unicode character), and return
5155 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005156*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005157PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005158_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005159{
Victor Stinner6099a032011-12-18 14:22:26 +01005160 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005161 void *data;
5162 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005163
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005164 if (!PyUnicode_Check(unicode)) {
5165 PyErr_BadArgument();
5166 return NULL;
5167 }
5168
5169 if (PyUnicode_READY(unicode) == -1)
5170 return NULL;
5171
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005172 if (PyUnicode_UTF8(unicode))
5173 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5174 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005175
5176 kind = PyUnicode_KIND(unicode);
5177 data = PyUnicode_DATA(unicode);
5178 size = PyUnicode_GET_LENGTH(unicode);
5179
Benjamin Petersonead6b532011-12-20 17:23:42 -06005180 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005181 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005182 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005183 case PyUnicode_1BYTE_KIND:
5184 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5185 assert(!PyUnicode_IS_ASCII(unicode));
5186 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5187 case PyUnicode_2BYTE_KIND:
5188 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5189 case PyUnicode_4BYTE_KIND:
5190 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005191 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005192}
5193
Alexander Belopolsky40018472011-02-26 01:02:56 +00005194PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005195PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5196 Py_ssize_t size,
5197 const char *errors)
5198{
5199 PyObject *v, *unicode;
5200
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005201 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005202 if (unicode == NULL)
5203 return NULL;
5204 v = _PyUnicode_AsUTF8String(unicode, errors);
5205 Py_DECREF(unicode);
5206 return v;
5207}
5208
5209PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005210PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005212 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005213}
5214
Walter Dörwald41980ca2007-08-16 21:55:45 +00005215/* --- UTF-32 Codec ------------------------------------------------------- */
5216
5217PyObject *
5218PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005219 Py_ssize_t size,
5220 const char *errors,
5221 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005222{
5223 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5224}
5225
5226PyObject *
5227PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005228 Py_ssize_t size,
5229 const char *errors,
5230 int *byteorder,
5231 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005232{
5233 const char *starts = s;
5234 Py_ssize_t startinpos;
5235 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005236 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005237 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005238 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005239 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005240 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005241 PyObject *errorHandler = NULL;
5242 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005243
Walter Dörwald41980ca2007-08-16 21:55:45 +00005244 q = (unsigned char *)s;
5245 e = q + size;
5246
5247 if (byteorder)
5248 bo = *byteorder;
5249
5250 /* Check for BOM marks (U+FEFF) in the input and adjust current
5251 byte order setting accordingly. In native mode, the leading BOM
5252 mark is skipped, in all other modes, it is copied to the output
5253 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005254 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005255 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005256 if (bom == 0x0000FEFF) {
5257 bo = -1;
5258 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005259 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005260 else if (bom == 0xFFFE0000) {
5261 bo = 1;
5262 q += 4;
5263 }
5264 if (byteorder)
5265 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266 }
5267
Victor Stinnere64322e2012-10-30 23:12:47 +01005268 if (q == e) {
5269 if (consumed)
5270 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005271 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005272 }
5273
Victor Stinnere64322e2012-10-30 23:12:47 +01005274#ifdef WORDS_BIGENDIAN
5275 le = bo < 0;
5276#else
5277 le = bo <= 0;
5278#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005279 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005280
Victor Stinner8f674cc2013-04-17 23:02:17 +02005281 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005282 writer.min_length = (e - q + 3) / 4;
5283 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005284 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005285
Victor Stinnere64322e2012-10-30 23:12:47 +01005286 while (1) {
5287 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005288 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005289
Victor Stinnere64322e2012-10-30 23:12:47 +01005290 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005291 enum PyUnicode_Kind kind = writer.kind;
5292 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005293 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005294 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005295 if (le) {
5296 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005297 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005298 if (ch > maxch)
5299 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005300 if (kind != PyUnicode_1BYTE_KIND &&
5301 Py_UNICODE_IS_SURROGATE(ch))
5302 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005303 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005304 q += 4;
5305 } while (q <= last);
5306 }
5307 else {
5308 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005309 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005310 if (ch > maxch)
5311 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005312 if (kind != PyUnicode_1BYTE_KIND &&
5313 Py_UNICODE_IS_SURROGATE(ch))
5314 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005315 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005316 q += 4;
5317 } while (q <= last);
5318 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005319 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005320 }
5321
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005322 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005323 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005324 startinpos = ((const char *)q) - starts;
5325 endinpos = startinpos + 4;
5326 }
5327 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005328 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005330 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005332 startinpos = ((const char *)q) - starts;
5333 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005335 else {
5336 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005337 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005338 goto onError;
5339 q += 4;
5340 continue;
5341 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005342 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005343 startinpos = ((const char *)q) - starts;
5344 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005345 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005346
5347 /* The remaining input chars are ignored if the callback
5348 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005349 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005350 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005351 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005352 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005353 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005354 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005355 }
5356
Walter Dörwald41980ca2007-08-16 21:55:45 +00005357 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005359
Walter Dörwald41980ca2007-08-16 21:55:45 +00005360 Py_XDECREF(errorHandler);
5361 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005363
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005365 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005366 Py_XDECREF(errorHandler);
5367 Py_XDECREF(exc);
5368 return NULL;
5369}
5370
5371PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005372_PyUnicode_EncodeUTF32(PyObject *str,
5373 const char *errors,
5374 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005375{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005376 enum PyUnicode_Kind kind;
5377 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005378 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005379 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005380 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005381#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005382 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005383#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005384 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005385#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005386 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005387 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005388 PyObject *errorHandler = NULL;
5389 PyObject *exc = NULL;
5390 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005391
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005392 if (!PyUnicode_Check(str)) {
5393 PyErr_BadArgument();
5394 return NULL;
5395 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005396 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005397 return NULL;
5398 kind = PyUnicode_KIND(str);
5399 data = PyUnicode_DATA(str);
5400 len = PyUnicode_GET_LENGTH(str);
5401
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005402 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005403 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005404 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005405 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005406 if (v == NULL)
5407 return NULL;
5408
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005409 /* output buffer is 4-bytes aligned */
5410 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005411 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005412 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005413 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005414 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005415 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005416
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005417 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005418 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005419 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005420 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005421 else
5422 encoding = "utf-32";
5423
5424 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005425 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5426 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005427 }
5428
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005429 pos = 0;
5430 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005431 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005432
5433 if (kind == PyUnicode_2BYTE_KIND) {
5434 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5435 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005436 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005437 else {
5438 assert(kind == PyUnicode_4BYTE_KIND);
5439 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5440 &out, native_ordering);
5441 }
5442 if (pos == len)
5443 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005444
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005445 rep = unicode_encode_call_errorhandler(
5446 errors, &errorHandler,
5447 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005448 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005449 if (!rep)
5450 goto error;
5451
5452 if (PyBytes_Check(rep)) {
5453 repsize = PyBytes_GET_SIZE(rep);
5454 if (repsize & 3) {
5455 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005456 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005457 "surrogates not allowed");
5458 goto error;
5459 }
5460 moreunits = repsize / 4;
5461 }
5462 else {
5463 assert(PyUnicode_Check(rep));
5464 if (PyUnicode_READY(rep) < 0)
5465 goto error;
5466 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5467 if (!PyUnicode_IS_ASCII(rep)) {
5468 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005469 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005470 "surrogates not allowed");
5471 goto error;
5472 }
5473 }
5474
5475 /* four bytes are reserved for each surrogate */
5476 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005477 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005478 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005479 /* integer overflow */
5480 PyErr_NoMemory();
5481 goto error;
5482 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005483 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005484 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005485 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005486 }
5487
5488 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005489 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005490 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005491 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005492 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005493 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5494 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005495 }
5496
5497 Py_CLEAR(rep);
5498 }
5499
5500 /* Cut back to size actually needed. This is necessary for, for example,
5501 encoding of a string containing isolated surrogates and the 'ignore'
5502 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005503 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005504 if (nsize != PyBytes_GET_SIZE(v))
5505 _PyBytes_Resize(&v, nsize);
5506 Py_XDECREF(errorHandler);
5507 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005508 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005509 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005510 error:
5511 Py_XDECREF(rep);
5512 Py_XDECREF(errorHandler);
5513 Py_XDECREF(exc);
5514 Py_XDECREF(v);
5515 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005516}
5517
Alexander Belopolsky40018472011-02-26 01:02:56 +00005518PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005519PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5520 Py_ssize_t size,
5521 const char *errors,
5522 int byteorder)
5523{
5524 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005525 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005526 if (tmp == NULL)
5527 return NULL;
5528 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5529 Py_DECREF(tmp);
5530 return result;
5531}
5532
5533PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005534PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005535{
Victor Stinnerb960b342011-11-20 19:12:52 +01005536 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005537}
5538
Guido van Rossumd57fd912000-03-10 22:53:23 +00005539/* --- UTF-16 Codec ------------------------------------------------------- */
5540
Tim Peters772747b2001-08-09 22:21:55 +00005541PyObject *
5542PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005543 Py_ssize_t size,
5544 const char *errors,
5545 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546{
Walter Dörwald69652032004-09-07 20:24:22 +00005547 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5548}
5549
5550PyObject *
5551PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005552 Py_ssize_t size,
5553 const char *errors,
5554 int *byteorder,
5555 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005556{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005557 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005558 Py_ssize_t startinpos;
5559 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005560 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005561 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005562 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005563 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005564 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005565 PyObject *errorHandler = NULL;
5566 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005567 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005568
Tim Peters772747b2001-08-09 22:21:55 +00005569 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005570 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005571
5572 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005573 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005574
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005575 /* Check for BOM marks (U+FEFF) in the input and adjust current
5576 byte order setting accordingly. In native mode, the leading BOM
5577 mark is skipped, in all other modes, it is copied to the output
5578 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005579 if (bo == 0 && size >= 2) {
5580 const Py_UCS4 bom = (q[1] << 8) | q[0];
5581 if (bom == 0xFEFF) {
5582 q += 2;
5583 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005584 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005585 else if (bom == 0xFFFE) {
5586 q += 2;
5587 bo = 1;
5588 }
5589 if (byteorder)
5590 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005591 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005592
Antoine Pitrou63065d72012-05-15 23:48:04 +02005593 if (q == e) {
5594 if (consumed)
5595 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005596 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005597 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005598
Christian Heimes743e0cd2012-10-17 23:52:17 +02005599#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005600 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005601 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005602#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005603 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005604 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005605#endif
Tim Peters772747b2001-08-09 22:21:55 +00005606
Antoine Pitrou63065d72012-05-15 23:48:04 +02005607 /* Note: size will always be longer than the resulting Unicode
5608 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005609 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005610 writer.min_length = (e - q + 1) / 2;
5611 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005612 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613
Antoine Pitrou63065d72012-05-15 23:48:04 +02005614 while (1) {
5615 Py_UCS4 ch = 0;
5616 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005617 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005618 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005619 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005620 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005621 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005622 native_ordering);
5623 else
5624 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005625 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005626 native_ordering);
5627 } else if (kind == PyUnicode_2BYTE_KIND) {
5628 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005629 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005630 native_ordering);
5631 } else {
5632 assert(kind == PyUnicode_4BYTE_KIND);
5633 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005634 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005635 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005636 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005637 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005638
Antoine Pitrou63065d72012-05-15 23:48:04 +02005639 switch (ch)
5640 {
5641 case 0:
5642 /* remaining byte at the end? (size should be even) */
5643 if (q == e || consumed)
5644 goto End;
5645 errmsg = "truncated data";
5646 startinpos = ((const char *)q) - starts;
5647 endinpos = ((const char *)e) - starts;
5648 break;
5649 /* The remaining input chars are ignored if the callback
5650 chooses to skip the input */
5651 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005652 q -= 2;
5653 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005654 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005655 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005656 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005657 endinpos = ((const char *)e) - starts;
5658 break;
5659 case 2:
5660 errmsg = "illegal encoding";
5661 startinpos = ((const char *)q) - 2 - starts;
5662 endinpos = startinpos + 2;
5663 break;
5664 case 3:
5665 errmsg = "illegal UTF-16 surrogate";
5666 startinpos = ((const char *)q) - 4 - starts;
5667 endinpos = startinpos + 2;
5668 break;
5669 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005670 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005671 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 continue;
5673 }
5674
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005675 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005676 errors,
5677 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005678 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005679 &starts,
5680 (const char **)&e,
5681 &startinpos,
5682 &endinpos,
5683 &exc,
5684 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005685 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005686 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687 }
5688
Antoine Pitrou63065d72012-05-15 23:48:04 +02005689End:
Walter Dörwald69652032004-09-07 20:24:22 +00005690 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005691 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005692
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005693 Py_XDECREF(errorHandler);
5694 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005695 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696
Benjamin Peterson29060642009-01-31 22:14:21 +00005697 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005698 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005699 Py_XDECREF(errorHandler);
5700 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005701 return NULL;
5702}
5703
Tim Peters772747b2001-08-09 22:21:55 +00005704PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005705_PyUnicode_EncodeUTF16(PyObject *str,
5706 const char *errors,
5707 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005708{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005709 enum PyUnicode_Kind kind;
5710 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005711 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005712 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005713 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005714 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005715#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005716 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005717#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005718 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005719#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005720 const char *encoding;
5721 Py_ssize_t nsize, pos;
5722 PyObject *errorHandler = NULL;
5723 PyObject *exc = NULL;
5724 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005725
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005726 if (!PyUnicode_Check(str)) {
5727 PyErr_BadArgument();
5728 return NULL;
5729 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005730 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005731 return NULL;
5732 kind = PyUnicode_KIND(str);
5733 data = PyUnicode_DATA(str);
5734 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005735
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005736 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005737 if (kind == PyUnicode_4BYTE_KIND) {
5738 const Py_UCS4 *in = (const Py_UCS4 *)data;
5739 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005740 while (in < end) {
5741 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005742 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005743 }
5744 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005745 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005746 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005747 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005748 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005749 nsize = len + pairs + (byteorder == 0);
5750 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005751 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005752 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005753 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005754
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005755 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005756 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005757 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005758 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005759 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005760 }
5761 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005762 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005763 }
Tim Peters772747b2001-08-09 22:21:55 +00005764
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005765 if (kind == PyUnicode_1BYTE_KIND) {
5766 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5767 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005768 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005769
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005770 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005771 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005772 }
5773 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005774 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005775 }
5776 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005777 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005778 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005779
5780 pos = 0;
5781 while (pos < len) {
5782 Py_ssize_t repsize, moreunits;
5783
5784 if (kind == PyUnicode_2BYTE_KIND) {
5785 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5786 &out, native_ordering);
5787 }
5788 else {
5789 assert(kind == PyUnicode_4BYTE_KIND);
5790 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5791 &out, native_ordering);
5792 }
5793 if (pos == len)
5794 break;
5795
5796 rep = unicode_encode_call_errorhandler(
5797 errors, &errorHandler,
5798 encoding, "surrogates not allowed",
5799 str, &exc, pos, pos + 1, &pos);
5800 if (!rep)
5801 goto error;
5802
5803 if (PyBytes_Check(rep)) {
5804 repsize = PyBytes_GET_SIZE(rep);
5805 if (repsize & 1) {
5806 raise_encode_exception(&exc, encoding,
5807 str, pos - 1, pos,
5808 "surrogates not allowed");
5809 goto error;
5810 }
5811 moreunits = repsize / 2;
5812 }
5813 else {
5814 assert(PyUnicode_Check(rep));
5815 if (PyUnicode_READY(rep) < 0)
5816 goto error;
5817 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5818 if (!PyUnicode_IS_ASCII(rep)) {
5819 raise_encode_exception(&exc, encoding,
5820 str, pos - 1, pos,
5821 "surrogates not allowed");
5822 goto error;
5823 }
5824 }
5825
5826 /* two bytes are reserved for each surrogate */
5827 if (moreunits > 1) {
5828 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005829 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005830 /* integer overflow */
5831 PyErr_NoMemory();
5832 goto error;
5833 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005834 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005835 goto error;
5836 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5837 }
5838
5839 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005840 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005841 out += moreunits;
5842 } else /* rep is unicode */ {
5843 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5844 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5845 &out, native_ordering);
5846 }
5847
5848 Py_CLEAR(rep);
5849 }
5850
5851 /* Cut back to size actually needed. This is necessary for, for example,
5852 encoding of a string containing isolated surrogates and the 'ignore' handler
5853 is used. */
5854 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5855 if (nsize != PyBytes_GET_SIZE(v))
5856 _PyBytes_Resize(&v, nsize);
5857 Py_XDECREF(errorHandler);
5858 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005859 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005860 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005861 error:
5862 Py_XDECREF(rep);
5863 Py_XDECREF(errorHandler);
5864 Py_XDECREF(exc);
5865 Py_XDECREF(v);
5866 return NULL;
5867#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868}
5869
Alexander Belopolsky40018472011-02-26 01:02:56 +00005870PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005871PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5872 Py_ssize_t size,
5873 const char *errors,
5874 int byteorder)
5875{
5876 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005877 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005878 if (tmp == NULL)
5879 return NULL;
5880 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5881 Py_DECREF(tmp);
5882 return result;
5883}
5884
5885PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005886PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005888 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889}
5890
5891/* --- Unicode Escape Codec ----------------------------------------------- */
5892
Fredrik Lundh06d12682001-01-24 07:59:11 +00005893static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005894
Alexander Belopolsky40018472011-02-26 01:02:56 +00005895PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005896_PyUnicode_DecodeUnicodeEscape(const char *s,
5897 Py_ssize_t size,
5898 const char *errors,
5899 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005900{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005901 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005902 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005904 PyObject *errorHandler = NULL;
5905 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005906
Eric V. Smith42454af2016-10-31 09:22:08 -04005907 // so we can remember if we've seen an invalid escape char or not
5908 *first_invalid_escape = NULL;
5909
Victor Stinner62ec3312016-09-06 17:04:34 -07005910 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005911 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005912 }
5913 /* Escaped strings will always be longer than the resulting
5914 Unicode string, so we start with size here and then reduce the
5915 length after conversion to the true value.
5916 (but if the error callback returns a long replacement string
5917 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005918 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005919 writer.min_length = size;
5920 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5921 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005922 }
5923
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924 end = s + size;
5925 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005926 unsigned char c = (unsigned char) *s++;
5927 Py_UCS4 ch;
5928 int count;
5929 Py_ssize_t startinpos;
5930 Py_ssize_t endinpos;
5931 const char *message;
5932
5933#define WRITE_ASCII_CHAR(ch) \
5934 do { \
5935 assert(ch <= 127); \
5936 assert(writer.pos < writer.size); \
5937 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5938 } while(0)
5939
5940#define WRITE_CHAR(ch) \
5941 do { \
5942 if (ch <= writer.maxchar) { \
5943 assert(writer.pos < writer.size); \
5944 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5945 } \
5946 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5947 goto onError; \
5948 } \
5949 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950
5951 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005952 if (c != '\\') {
5953 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 continue;
5955 }
5956
Victor Stinner62ec3312016-09-06 17:04:34 -07005957 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005959 if (s >= end) {
5960 message = "\\ at end of string";
5961 goto error;
5962 }
5963 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005964
Victor Stinner62ec3312016-09-06 17:04:34 -07005965 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005966 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005969 case '\n': continue;
5970 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5971 case '\'': WRITE_ASCII_CHAR('\''); continue;
5972 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5973 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005974 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005975 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5976 case 't': WRITE_ASCII_CHAR('\t'); continue;
5977 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5978 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005979 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005980 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005981 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005982 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983
Benjamin Peterson29060642009-01-31 22:14:21 +00005984 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 case '0': case '1': case '2': case '3':
5986 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005987 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005988 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005989 ch = (ch<<3) + *s++ - '0';
5990 if (s < end && '0' <= *s && *s <= '7') {
5991 ch = (ch<<3) + *s++ - '0';
5992 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005994 WRITE_CHAR(ch);
5995 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005996
Benjamin Peterson29060642009-01-31 22:14:21 +00005997 /* hex escapes */
5998 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006000 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006001 message = "truncated \\xXX escape";
6002 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006006 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006007 message = "truncated \\uXXXX escape";
6008 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009
Benjamin Peterson29060642009-01-31 22:14:21 +00006010 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006011 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006012 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006013 message = "truncated \\UXXXXXXXX escape";
6014 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006015 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006016 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006017 ch <<= 4;
6018 if (c >= '0' && c <= '9') {
6019 ch += c - '0';
6020 }
6021 else if (c >= 'a' && c <= 'f') {
6022 ch += c - ('a' - 10);
6023 }
6024 else if (c >= 'A' && c <= 'F') {
6025 ch += c - ('A' - 10);
6026 }
6027 else {
6028 break;
6029 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006030 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006031 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006032 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006033 }
6034
6035 /* when we get here, ch is a 32-bit unicode character */
6036 if (ch > MAX_UNICODE) {
6037 message = "illegal Unicode character";
6038 goto error;
6039 }
6040
6041 WRITE_CHAR(ch);
6042 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006043
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006045 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006046 if (ucnhash_CAPI == NULL) {
6047 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006048 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6049 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006050 if (ucnhash_CAPI == NULL) {
6051 PyErr_SetString(
6052 PyExc_UnicodeError,
6053 "\\N escapes not supported (can't load unicodedata module)"
6054 );
6055 goto onError;
6056 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006057 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006058
6059 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006060 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006061 const char *start = ++s;
6062 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006063 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006064 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006065 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006066 namelen = s - start;
6067 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006068 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006069 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006070 ch = 0xffffffff; /* in case 'getcode' messes up */
6071 if (namelen <= INT_MAX &&
6072 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6073 &ch, 0)) {
6074 assert(ch <= MAX_UNICODE);
6075 WRITE_CHAR(ch);
6076 continue;
6077 }
6078 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006079 }
6080 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006081 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006082
6083 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006084 if (*first_invalid_escape == NULL) {
6085 *first_invalid_escape = s-1; /* Back up one char, since we've
6086 already incremented s. */
6087 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006088 WRITE_ASCII_CHAR('\\');
6089 WRITE_CHAR(c);
6090 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006092
6093 error:
6094 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006095 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006096 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006097 errors, &errorHandler,
6098 "unicodeescape", message,
6099 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006100 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006101 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006102 }
6103 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6104 goto onError;
6105 }
6106
6107#undef WRITE_ASCII_CHAR
6108#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006110
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006111 Py_XDECREF(errorHandler);
6112 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006113 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006114
Benjamin Peterson29060642009-01-31 22:14:21 +00006115 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006116 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006117 Py_XDECREF(errorHandler);
6118 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006119 return NULL;
6120}
6121
Eric V. Smith42454af2016-10-31 09:22:08 -04006122PyObject *
6123PyUnicode_DecodeUnicodeEscape(const char *s,
6124 Py_ssize_t size,
6125 const char *errors)
6126{
6127 const char *first_invalid_escape;
6128 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6129 &first_invalid_escape);
6130 if (result == NULL)
6131 return NULL;
6132 if (first_invalid_escape != NULL) {
6133 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6134 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006135 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006136 Py_DECREF(result);
6137 return NULL;
6138 }
6139 }
6140 return result;
6141}
6142
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006143/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144
Alexander Belopolsky40018472011-02-26 01:02:56 +00006145PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006146PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006147{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006148 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006149 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006151 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006152 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006153 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154
Ezio Melottie7f90372012-10-05 03:33:31 +03006155 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006156 escape.
6157
Ezio Melottie7f90372012-10-05 03:33:31 +03006158 For UCS1 strings it's '\xxx', 4 bytes per source character.
6159 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6160 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006161 */
6162
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006163 if (!PyUnicode_Check(unicode)) {
6164 PyErr_BadArgument();
6165 return NULL;
6166 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006167 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006168 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006169 }
Victor Stinner358af132015-10-12 22:36:57 +02006170
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006172 if (len == 0) {
6173 return PyBytes_FromStringAndSize(NULL, 0);
6174 }
6175
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006176 kind = PyUnicode_KIND(unicode);
6177 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006178 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6179 bytes, and 1 byte characters 4. */
6180 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006181 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006182 return PyErr_NoMemory();
6183 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006184 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006185 if (repr == NULL) {
6186 return NULL;
6187 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006188
Victor Stinner62ec3312016-09-06 17:04:34 -07006189 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006191 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006192
Victor Stinner62ec3312016-09-06 17:04:34 -07006193 /* U+0000-U+00ff range */
6194 if (ch < 0x100) {
6195 if (ch >= ' ' && ch < 127) {
6196 if (ch != '\\') {
6197 /* Copy printable US ASCII as-is */
6198 *p++ = (char) ch;
6199 }
6200 /* Escape backslashes */
6201 else {
6202 *p++ = '\\';
6203 *p++ = '\\';
6204 }
6205 }
Victor Stinner358af132015-10-12 22:36:57 +02006206
Victor Stinner62ec3312016-09-06 17:04:34 -07006207 /* Map special whitespace to '\t', \n', '\r' */
6208 else if (ch == '\t') {
6209 *p++ = '\\';
6210 *p++ = 't';
6211 }
6212 else if (ch == '\n') {
6213 *p++ = '\\';
6214 *p++ = 'n';
6215 }
6216 else if (ch == '\r') {
6217 *p++ = '\\';
6218 *p++ = 'r';
6219 }
6220
6221 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6222 else {
6223 *p++ = '\\';
6224 *p++ = 'x';
6225 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6226 *p++ = Py_hexdigits[ch & 0x000F];
6227 }
Tim Petersced69f82003-09-16 20:30:58 +00006228 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006229 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006230 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231 *p++ = '\\';
6232 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006233 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6234 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6235 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6236 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006238 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6239 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006240
Victor Stinner62ec3312016-09-06 17:04:34 -07006241 /* Make sure that the first two digits are zero */
6242 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006243 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006244 *p++ = 'U';
6245 *p++ = '0';
6246 *p++ = '0';
6247 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6248 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6249 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6250 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6251 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6252 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006253 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006255
Victor Stinner62ec3312016-09-06 17:04:34 -07006256 assert(p - PyBytes_AS_STRING(repr) > 0);
6257 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6258 return NULL;
6259 }
6260 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006261}
6262
Alexander Belopolsky40018472011-02-26 01:02:56 +00006263PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006264PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6265 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006266{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006267 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006268 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006269 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006270 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006271 }
6272
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006273 result = PyUnicode_AsUnicodeEscapeString(tmp);
6274 Py_DECREF(tmp);
6275 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006276}
6277
6278/* --- Raw Unicode Escape Codec ------------------------------------------- */
6279
Alexander Belopolsky40018472011-02-26 01:02:56 +00006280PyObject *
6281PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006282 Py_ssize_t size,
6283 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006285 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006286 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006287 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006288 PyObject *errorHandler = NULL;
6289 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006290
Victor Stinner62ec3312016-09-06 17:04:34 -07006291 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006292 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006293 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006294
Guido van Rossumd57fd912000-03-10 22:53:23 +00006295 /* Escaped strings will always be longer than the resulting
6296 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006297 length after conversion to the true value. (But decoding error
6298 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006299 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006300 writer.min_length = size;
6301 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6302 goto onError;
6303 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006304
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305 end = s + size;
6306 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006307 unsigned char c = (unsigned char) *s++;
6308 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006309 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006310 Py_ssize_t startinpos;
6311 Py_ssize_t endinpos;
6312 const char *message;
6313
6314#define WRITE_CHAR(ch) \
6315 do { \
6316 if (ch <= writer.maxchar) { \
6317 assert(writer.pos < writer.size); \
6318 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6319 } \
6320 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6321 goto onError; \
6322 } \
6323 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324
Benjamin Peterson29060642009-01-31 22:14:21 +00006325 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006326 if (c != '\\' || s >= end) {
6327 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006328 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006329 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006330
Victor Stinner62ec3312016-09-06 17:04:34 -07006331 c = (unsigned char) *s++;
6332 if (c == 'u') {
6333 count = 4;
6334 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006335 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006336 else if (c == 'U') {
6337 count = 8;
6338 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006339 }
6340 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006341 assert(writer.pos < writer.size);
6342 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6343 WRITE_CHAR(c);
6344 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006345 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006346 startinpos = s - starts - 2;
6347
6348 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6349 for (ch = 0; count && s < end; ++s, --count) {
6350 c = (unsigned char)*s;
6351 ch <<= 4;
6352 if (c >= '0' && c <= '9') {
6353 ch += c - '0';
6354 }
6355 else if (c >= 'a' && c <= 'f') {
6356 ch += c - ('a' - 10);
6357 }
6358 else if (c >= 'A' && c <= 'F') {
6359 ch += c - ('A' - 10);
6360 }
6361 else {
6362 break;
6363 }
6364 }
6365 if (!count) {
6366 if (ch <= MAX_UNICODE) {
6367 WRITE_CHAR(ch);
6368 continue;
6369 }
6370 message = "\\Uxxxxxxxx out of range";
6371 }
6372
6373 endinpos = s-starts;
6374 writer.min_length = end - s + writer.pos;
6375 if (unicode_decode_call_errorhandler_writer(
6376 errors, &errorHandler,
6377 "rawunicodeescape", message,
6378 &starts, &end, &startinpos, &endinpos, &exc, &s,
6379 &writer)) {
6380 goto onError;
6381 }
6382 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6383 goto onError;
6384 }
6385
6386#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006387 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388 Py_XDECREF(errorHandler);
6389 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006390 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006391
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006393 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394 Py_XDECREF(errorHandler);
6395 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006396 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006397
Guido van Rossumd57fd912000-03-10 22:53:23 +00006398}
6399
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006400
Alexander Belopolsky40018472011-02-26 01:02:56 +00006401PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006402PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006403{
Victor Stinner62ec3312016-09-06 17:04:34 -07006404 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006405 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006407 int kind;
6408 void *data;
6409 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006410
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006411 if (!PyUnicode_Check(unicode)) {
6412 PyErr_BadArgument();
6413 return NULL;
6414 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006415 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006416 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006417 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006418 kind = PyUnicode_KIND(unicode);
6419 data = PyUnicode_DATA(unicode);
6420 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006421 if (kind == PyUnicode_1BYTE_KIND) {
6422 return PyBytes_FromStringAndSize(data, len);
6423 }
Victor Stinner0e368262011-11-10 20:12:49 +01006424
Victor Stinner62ec3312016-09-06 17:04:34 -07006425 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6426 bytes, and 1 byte characters 4. */
6427 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006428
Victor Stinner62ec3312016-09-06 17:04:34 -07006429 if (len > PY_SSIZE_T_MAX / expandsize) {
6430 return PyErr_NoMemory();
6431 }
6432 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6433 if (repr == NULL) {
6434 return NULL;
6435 }
6436 if (len == 0) {
6437 return repr;
6438 }
6439
6440 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006441 for (pos = 0; pos < len; pos++) {
6442 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006443
Victor Stinner62ec3312016-09-06 17:04:34 -07006444 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6445 if (ch < 0x100) {
6446 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006447 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006448 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6449 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006450 *p++ = '\\';
6451 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006452 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6453 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6454 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6455 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006456 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006457 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6458 else {
6459 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6460 *p++ = '\\';
6461 *p++ = 'U';
6462 *p++ = '0';
6463 *p++ = '0';
6464 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6465 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6466 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6467 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6468 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6469 *p++ = Py_hexdigits[ch & 15];
6470 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006471 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006472
Victor Stinner62ec3312016-09-06 17:04:34 -07006473 assert(p > PyBytes_AS_STRING(repr));
6474 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6475 return NULL;
6476 }
6477 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006478}
6479
Alexander Belopolsky40018472011-02-26 01:02:56 +00006480PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006481PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6482 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006483{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006484 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006485 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006486 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006487 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006488 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6489 Py_DECREF(tmp);
6490 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006491}
6492
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006493/* --- Unicode Internal Codec ------------------------------------------- */
6494
Alexander Belopolsky40018472011-02-26 01:02:56 +00006495PyObject *
6496_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006497 Py_ssize_t size,
6498 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006499{
6500 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006501 Py_ssize_t startinpos;
6502 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006503 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006504 const char *end;
6505 const char *reason;
6506 PyObject *errorHandler = NULL;
6507 PyObject *exc = NULL;
6508
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006509 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006510 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006511 1))
6512 return NULL;
6513
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006514 if (size < 0) {
6515 PyErr_BadInternalCall();
6516 return NULL;
6517 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006518 if (size == 0)
6519 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006520
Victor Stinner8f674cc2013-04-17 23:02:17 +02006521 _PyUnicodeWriter_Init(&writer);
6522 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6523 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006525 }
6526 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006527
Victor Stinner8f674cc2013-04-17 23:02:17 +02006528 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006529 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006530 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006531 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006532 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006533 endinpos = end-starts;
6534 reason = "truncated input";
6535 goto error;
6536 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006537 /* We copy the raw representation one byte at a time because the
6538 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006539 ((char *) &uch)[0] = s[0];
6540 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006541#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006542 ((char *) &uch)[2] = s[2];
6543 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006544#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006545 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006546#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006547 /* We have to sanity check the raw data, otherwise doom looms for
6548 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006549 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006550 endinpos = s - starts + Py_UNICODE_SIZE;
6551 reason = "illegal code point (> 0x10FFFF)";
6552 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006553 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006554#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006555 s += Py_UNICODE_SIZE;
6556#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006557 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006558 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006559 Py_UNICODE uch2;
6560 ((char *) &uch2)[0] = s[0];
6561 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006562 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006563 {
Victor Stinner551ac952011-11-29 22:58:13 +01006564 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006565 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006566 }
6567 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006568#endif
6569
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006570 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006571 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006572 continue;
6573
6574 error:
6575 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006576 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006577 errors, &errorHandler,
6578 "unicode_internal", reason,
6579 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006580 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006581 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006582 }
6583
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006584 Py_XDECREF(errorHandler);
6585 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006586 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006587
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006589 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006590 Py_XDECREF(errorHandler);
6591 Py_XDECREF(exc);
6592 return NULL;
6593}
6594
Guido van Rossumd57fd912000-03-10 22:53:23 +00006595/* --- Latin-1 Codec ------------------------------------------------------ */
6596
Alexander Belopolsky40018472011-02-26 01:02:56 +00006597PyObject *
6598PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006599 Py_ssize_t size,
6600 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006601{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006602 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006603 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006604}
6605
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006606/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006607static void
6608make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006609 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006610 PyObject *unicode,
6611 Py_ssize_t startpos, Py_ssize_t endpos,
6612 const char *reason)
6613{
6614 if (*exceptionObject == NULL) {
6615 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006616 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006617 encoding, unicode, startpos, endpos, reason);
6618 }
6619 else {
6620 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6621 goto onError;
6622 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6623 goto onError;
6624 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6625 goto onError;
6626 return;
6627 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006628 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006629 }
6630}
6631
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006632/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006633static void
6634raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006635 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006636 PyObject *unicode,
6637 Py_ssize_t startpos, Py_ssize_t endpos,
6638 const char *reason)
6639{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006640 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006641 encoding, unicode, startpos, endpos, reason);
6642 if (*exceptionObject != NULL)
6643 PyCodec_StrictErrors(*exceptionObject);
6644}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006645
6646/* error handling callback helper:
6647 build arguments, call the callback and check the arguments,
6648 put the result into newpos and return the replacement string, which
6649 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006650static PyObject *
6651unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006652 PyObject **errorHandler,
6653 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006654 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006655 Py_ssize_t startpos, Py_ssize_t endpos,
6656 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006657{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006658 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006659 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006660 PyObject *restuple;
6661 PyObject *resunicode;
6662
6663 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006664 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006665 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006667 }
6668
Benjamin Petersonbac79492012-01-14 13:34:47 -05006669 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006670 return NULL;
6671 len = PyUnicode_GET_LENGTH(unicode);
6672
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006673 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006674 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006675 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006677
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006678 restuple = PyObject_CallFunctionObjArgs(
6679 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006680 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006681 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006683 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006684 Py_DECREF(restuple);
6685 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006687 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006688 &resunicode, newpos)) {
6689 Py_DECREF(restuple);
6690 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006692 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6693 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6694 Py_DECREF(restuple);
6695 return NULL;
6696 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006698 *newpos = len + *newpos;
6699 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006700 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006701 Py_DECREF(restuple);
6702 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006703 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704 Py_INCREF(resunicode);
6705 Py_DECREF(restuple);
6706 return resunicode;
6707}
6708
Alexander Belopolsky40018472011-02-26 01:02:56 +00006709static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006711 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006712 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006713{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006714 /* input state */
6715 Py_ssize_t pos=0, size;
6716 int kind;
6717 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718 /* pointer into the output */
6719 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006720 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6721 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006722 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006723 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006724 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006725 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006726 /* output object */
6727 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006728
Benjamin Petersonbac79492012-01-14 13:34:47 -05006729 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 return NULL;
6731 size = PyUnicode_GET_LENGTH(unicode);
6732 kind = PyUnicode_KIND(unicode);
6733 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006734 /* allocate enough for a simple encoding without
6735 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006736 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006737 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006738
6739 _PyBytesWriter_Init(&writer);
6740 str = _PyBytesWriter_Alloc(&writer, size);
6741 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006742 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006743
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006744 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006745 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006746
Benjamin Peterson29060642009-01-31 22:14:21 +00006747 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006748 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006750 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006751 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006752 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006753 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006754 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006756 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006757 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006759
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006760 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006761 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006762
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006763 /* Only overallocate the buffer if it's not the last write */
6764 writer.overallocate = (collend < size);
6765
Benjamin Peterson29060642009-01-31 22:14:21 +00006766 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006767 if (error_handler == _Py_ERROR_UNKNOWN)
6768 error_handler = get_error_handler(errors);
6769
6770 switch (error_handler) {
6771 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006772 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006773 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006774
6775 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006776 memset(str, '?', collend - collstart);
6777 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006778 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006779 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006780 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006781 break;
Victor Stinner50149202015-09-22 00:26:54 +02006782
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006783 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006784 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006785 writer.min_size -= (collend - collstart);
6786 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006787 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006788 if (str == NULL)
6789 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006790 pos = collend;
6791 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006792
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006793 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006794 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006795 writer.min_size -= (collend - collstart);
6796 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006797 unicode, collstart, collend);
6798 if (str == NULL)
6799 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006800 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006801 break;
Victor Stinner50149202015-09-22 00:26:54 +02006802
Victor Stinnerc3713e92015-09-29 12:32:13 +02006803 case _Py_ERROR_SURROGATEESCAPE:
6804 for (i = collstart; i < collend; ++i) {
6805 ch = PyUnicode_READ(kind, data, i);
6806 if (ch < 0xdc80 || 0xdcff < ch) {
6807 /* Not a UTF-8b surrogate */
6808 break;
6809 }
6810 *str++ = (char)(ch - 0xdc00);
6811 ++pos;
6812 }
6813 if (i >= collend)
6814 break;
6815 collstart = pos;
6816 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006817 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006818
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006820 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6821 encoding, reason, unicode, &exc,
6822 collstart, collend, &newpos);
6823 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006824 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006825
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006826 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006827 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006828
Victor Stinner6bd525b2015-10-09 13:10:05 +02006829 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006830 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006831 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006832 PyBytes_AS_STRING(rep),
6833 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006834 if (str == NULL)
6835 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006836 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006837 else {
6838 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006839
Victor Stinner6bd525b2015-10-09 13:10:05 +02006840 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006841 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006842
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006843 if (limit == 256 ?
6844 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6845 !PyUnicode_IS_ASCII(rep))
6846 {
6847 /* Not all characters are smaller than limit */
6848 raise_encode_exception(&exc, encoding, unicode,
6849 collstart, collend, reason);
6850 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006851 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006852 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6853 str = _PyBytesWriter_WriteBytes(&writer, str,
6854 PyUnicode_DATA(rep),
6855 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006856 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006857 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006858 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006859 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006860
6861 /* If overallocation was disabled, ensure that it was the last
6862 write. Otherwise, we missed an optimization */
6863 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006864 }
6865 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006866
Victor Stinner50149202015-09-22 00:26:54 +02006867 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006868 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006869 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006870
6871 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006872 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006873 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006874 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006875 Py_XDECREF(exc);
6876 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006877}
6878
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006879/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006880PyObject *
6881PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006882 Py_ssize_t size,
6883 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006884{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006885 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006886 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006887 if (unicode == NULL)
6888 return NULL;
6889 result = unicode_encode_ucs1(unicode, errors, 256);
6890 Py_DECREF(unicode);
6891 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006892}
6893
Alexander Belopolsky40018472011-02-26 01:02:56 +00006894PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006895_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006896{
6897 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006898 PyErr_BadArgument();
6899 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006900 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006901 if (PyUnicode_READY(unicode) == -1)
6902 return NULL;
6903 /* Fast path: if it is a one-byte string, construct
6904 bytes object directly. */
6905 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6906 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6907 PyUnicode_GET_LENGTH(unicode));
6908 /* Non-Latin-1 characters present. Defer to above function to
6909 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006910 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006911}
6912
6913PyObject*
6914PyUnicode_AsLatin1String(PyObject *unicode)
6915{
6916 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006917}
6918
6919/* --- 7-bit ASCII Codec -------------------------------------------------- */
6920
Alexander Belopolsky40018472011-02-26 01:02:56 +00006921PyObject *
6922PyUnicode_DecodeASCII(const char *s,
6923 Py_ssize_t size,
6924 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006925{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006926 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006927 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006928 int kind;
6929 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006930 Py_ssize_t startinpos;
6931 Py_ssize_t endinpos;
6932 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006933 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006934 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006935 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006936 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006937
Guido van Rossumd57fd912000-03-10 22:53:23 +00006938 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006939 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006940
Guido van Rossumd57fd912000-03-10 22:53:23 +00006941 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006942 if (size == 1 && (unsigned char)s[0] < 128)
6943 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006944
Victor Stinner8f674cc2013-04-17 23:02:17 +02006945 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006946 writer.min_length = size;
6947 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006948 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006949
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006950 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006951 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006952 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006953 writer.pos = outpos;
6954 if (writer.pos == size)
6955 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006956
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006957 s += writer.pos;
6958 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006959 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006960 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006961 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006962 PyUnicode_WRITE(kind, data, writer.pos, c);
6963 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006964 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006965 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006966 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006967
6968 /* byte outsize range 0x00..0x7f: call the error handler */
6969
6970 if (error_handler == _Py_ERROR_UNKNOWN)
6971 error_handler = get_error_handler(errors);
6972
6973 switch (error_handler)
6974 {
6975 case _Py_ERROR_REPLACE:
6976 case _Py_ERROR_SURROGATEESCAPE:
6977 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006978 but we may switch to UCS2 at the first write */
6979 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6980 goto onError;
6981 kind = writer.kind;
6982 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006983
6984 if (error_handler == _Py_ERROR_REPLACE)
6985 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6986 else
6987 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6988 writer.pos++;
6989 ++s;
6990 break;
6991
6992 case _Py_ERROR_IGNORE:
6993 ++s;
6994 break;
6995
6996 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006997 startinpos = s-starts;
6998 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006999 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007000 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007001 "ascii", "ordinal not in range(128)",
7002 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007003 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007004 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007005 kind = writer.kind;
7006 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007008 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007009 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007010 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007011 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007012
Benjamin Peterson29060642009-01-31 22:14:21 +00007013 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007014 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007015 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007016 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007017 return NULL;
7018}
7019
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007020/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007021PyObject *
7022PyUnicode_EncodeASCII(const Py_UNICODE *p,
7023 Py_ssize_t size,
7024 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007025{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007026 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007027 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007028 if (unicode == NULL)
7029 return NULL;
7030 result = unicode_encode_ucs1(unicode, errors, 128);
7031 Py_DECREF(unicode);
7032 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007033}
7034
Alexander Belopolsky40018472011-02-26 01:02:56 +00007035PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007036_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007037{
7038 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007039 PyErr_BadArgument();
7040 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007042 if (PyUnicode_READY(unicode) == -1)
7043 return NULL;
7044 /* Fast path: if it is an ASCII-only string, construct bytes object
7045 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007046 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007047 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7048 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007049 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007050}
7051
7052PyObject *
7053PyUnicode_AsASCIIString(PyObject *unicode)
7054{
7055 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007056}
7057
Steve Dowercc16be82016-09-08 10:35:16 -07007058#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007059
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007060/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007061
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007062#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063#define NEED_RETRY
7064#endif
7065
Victor Stinner3a50e702011-10-18 21:21:00 +02007066#ifndef WC_ERR_INVALID_CHARS
7067# define WC_ERR_INVALID_CHARS 0x0080
7068#endif
7069
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007070static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007071code_page_name(UINT code_page, PyObject **obj)
7072{
7073 *obj = NULL;
7074 if (code_page == CP_ACP)
7075 return "mbcs";
7076 if (code_page == CP_UTF7)
7077 return "CP_UTF7";
7078 if (code_page == CP_UTF8)
7079 return "CP_UTF8";
7080
7081 *obj = PyBytes_FromFormat("cp%u", code_page);
7082 if (*obj == NULL)
7083 return NULL;
7084 return PyBytes_AS_STRING(*obj);
7085}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086
Victor Stinner3a50e702011-10-18 21:21:00 +02007087static DWORD
7088decode_code_page_flags(UINT code_page)
7089{
7090 if (code_page == CP_UTF7) {
7091 /* The CP_UTF7 decoder only supports flags=0 */
7092 return 0;
7093 }
7094 else
7095 return MB_ERR_INVALID_CHARS;
7096}
7097
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 * Decode a byte string from a Windows code page into unicode object in strict
7100 * mode.
7101 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007102 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7103 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007104 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007105static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007106decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007107 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 const char *in,
7109 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110{
Victor Stinner3a50e702011-10-18 21:21:00 +02007111 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007112 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114
7115 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007116 assert(insize > 0);
7117 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7118 if (outsize <= 0)
7119 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007120
7121 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007122 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007123 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007124 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007125 if (*v == NULL)
7126 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007127 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007128 }
7129 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007130 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007131 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007132 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007133 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007134 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007135 }
7136
7137 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7139 if (outsize <= 0)
7140 goto error;
7141 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007142
Victor Stinner3a50e702011-10-18 21:21:00 +02007143error:
7144 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7145 return -2;
7146 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007147 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007148}
7149
Victor Stinner3a50e702011-10-18 21:21:00 +02007150/*
7151 * Decode a byte string from a code page into unicode object with an error
7152 * handler.
7153 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007154 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 * UnicodeDecodeError exception and returns -1 on error.
7156 */
7157static int
7158decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007159 PyObject **v,
7160 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007161 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007162{
7163 const char *startin = in;
7164 const char *endin = in + size;
7165 const DWORD flags = decode_code_page_flags(code_page);
7166 /* Ideally, we should get reason from FormatMessage. This is the Windows
7167 2000 English version of the message. */
7168 const char *reason = "No mapping for the Unicode character exists "
7169 "in the target code page.";
7170 /* each step cannot decode more than 1 character, but a character can be
7171 represented as a surrogate pair */
7172 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007173 int insize;
7174 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 PyObject *errorHandler = NULL;
7176 PyObject *exc = NULL;
7177 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007178 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 DWORD err;
7180 int ret = -1;
7181
7182 assert(size > 0);
7183
7184 encoding = code_page_name(code_page, &encoding_obj);
7185 if (encoding == NULL)
7186 return -1;
7187
Victor Stinner7d00cc12014-03-17 23:08:06 +01007188 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007189 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7190 UnicodeDecodeError. */
7191 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7192 if (exc != NULL) {
7193 PyCodec_StrictErrors(exc);
7194 Py_CLEAR(exc);
7195 }
7196 goto error;
7197 }
7198
7199 if (*v == NULL) {
7200 /* Create unicode object */
7201 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7202 PyErr_NoMemory();
7203 goto error;
7204 }
Victor Stinnerab595942011-12-17 04:59:06 +01007205 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007206 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 if (*v == NULL)
7208 goto error;
7209 startout = PyUnicode_AS_UNICODE(*v);
7210 }
7211 else {
7212 /* Extend unicode object */
7213 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7214 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7215 PyErr_NoMemory();
7216 goto error;
7217 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007218 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 goto error;
7220 startout = PyUnicode_AS_UNICODE(*v) + n;
7221 }
7222
7223 /* Decode the byte string character per character */
7224 out = startout;
7225 while (in < endin)
7226 {
7227 /* Decode a character */
7228 insize = 1;
7229 do
7230 {
7231 outsize = MultiByteToWideChar(code_page, flags,
7232 in, insize,
7233 buffer, Py_ARRAY_LENGTH(buffer));
7234 if (outsize > 0)
7235 break;
7236 err = GetLastError();
7237 if (err != ERROR_NO_UNICODE_TRANSLATION
7238 && err != ERROR_INSUFFICIENT_BUFFER)
7239 {
7240 PyErr_SetFromWindowsErr(0);
7241 goto error;
7242 }
7243 insize++;
7244 }
7245 /* 4=maximum length of a UTF-8 sequence */
7246 while (insize <= 4 && (in + insize) <= endin);
7247
7248 if (outsize <= 0) {
7249 Py_ssize_t startinpos, endinpos, outpos;
7250
Victor Stinner7d00cc12014-03-17 23:08:06 +01007251 /* last character in partial decode? */
7252 if (in + insize >= endin && !final)
7253 break;
7254
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 startinpos = in - startin;
7256 endinpos = startinpos + 1;
7257 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007258 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 errors, &errorHandler,
7260 encoding, reason,
7261 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007262 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007263 {
7264 goto error;
7265 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007266 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007267 }
7268 else {
7269 in += insize;
7270 memcpy(out, buffer, outsize * sizeof(wchar_t));
7271 out += outsize;
7272 }
7273 }
7274
7275 /* write a NUL character at the end */
7276 *out = 0;
7277
7278 /* Extend unicode object */
7279 outsize = out - startout;
7280 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007281 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007282 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007283 /* (in - startin) <= size and size is an int */
7284 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007285
7286error:
7287 Py_XDECREF(encoding_obj);
7288 Py_XDECREF(errorHandler);
7289 Py_XDECREF(exc);
7290 return ret;
7291}
7292
Victor Stinner3a50e702011-10-18 21:21:00 +02007293static PyObject *
7294decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007295 const char *s, Py_ssize_t size,
7296 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007297{
Victor Stinner76a31a62011-11-04 00:05:13 +01007298 PyObject *v = NULL;
7299 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007300
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 if (code_page < 0) {
7302 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7303 return NULL;
7304 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007305 if (size < 0) {
7306 PyErr_BadInternalCall();
7307 return NULL;
7308 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007309
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007310 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007311 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007312
Victor Stinner76a31a62011-11-04 00:05:13 +01007313 do
7314 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007315#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007316 if (size > INT_MAX) {
7317 chunk_size = INT_MAX;
7318 final = 0;
7319 done = 0;
7320 }
7321 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007322#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007323 {
7324 chunk_size = (int)size;
7325 final = (consumed == NULL);
7326 done = 1;
7327 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007328
Victor Stinner76a31a62011-11-04 00:05:13 +01007329 if (chunk_size == 0 && done) {
7330 if (v != NULL)
7331 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007332 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007333 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007334
Victor Stinner76a31a62011-11-04 00:05:13 +01007335 converted = decode_code_page_strict(code_page, &v,
7336 s, chunk_size);
7337 if (converted == -2)
7338 converted = decode_code_page_errors(code_page, &v,
7339 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007340 errors, final);
7341 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007342
7343 if (converted < 0) {
7344 Py_XDECREF(v);
7345 return NULL;
7346 }
7347
7348 if (consumed)
7349 *consumed += converted;
7350
7351 s += converted;
7352 size -= converted;
7353 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007354
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007355 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007356}
7357
Alexander Belopolsky40018472011-02-26 01:02:56 +00007358PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007359PyUnicode_DecodeCodePageStateful(int code_page,
7360 const char *s,
7361 Py_ssize_t size,
7362 const char *errors,
7363 Py_ssize_t *consumed)
7364{
7365 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7366}
7367
7368PyObject *
7369PyUnicode_DecodeMBCSStateful(const char *s,
7370 Py_ssize_t size,
7371 const char *errors,
7372 Py_ssize_t *consumed)
7373{
7374 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7375}
7376
7377PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007378PyUnicode_DecodeMBCS(const char *s,
7379 Py_ssize_t size,
7380 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007381{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007382 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7383}
7384
Victor Stinner3a50e702011-10-18 21:21:00 +02007385static DWORD
7386encode_code_page_flags(UINT code_page, const char *errors)
7387{
7388 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007389 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 }
7391 else if (code_page == CP_UTF7) {
7392 /* CP_UTF7 only supports flags=0 */
7393 return 0;
7394 }
7395 else {
7396 if (errors != NULL && strcmp(errors, "replace") == 0)
7397 return 0;
7398 else
7399 return WC_NO_BEST_FIT_CHARS;
7400 }
7401}
7402
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007403/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007404 * Encode a Unicode string to a Windows code page into a byte string in strict
7405 * mode.
7406 *
7407 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007408 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007409 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007410static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007411encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007412 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007413 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007414{
Victor Stinner554f3f02010-06-16 23:33:54 +00007415 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 BOOL *pusedDefaultChar = &usedDefaultChar;
7417 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007418 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007419 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 const DWORD flags = encode_code_page_flags(code_page, NULL);
7421 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007422 /* Create a substring so that we can get the UTF-16 representation
7423 of just the slice under consideration. */
7424 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007425
Martin v. Löwis3d325192011-11-04 18:23:06 +01007426 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007427
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007429 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007431 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007432
Victor Stinner2fc507f2011-11-04 20:06:39 +01007433 substring = PyUnicode_Substring(unicode, offset, offset+len);
7434 if (substring == NULL)
7435 return -1;
7436 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7437 if (p == NULL) {
7438 Py_DECREF(substring);
7439 return -1;
7440 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007441 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007442
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007443 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007445 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 NULL, 0,
7447 NULL, pusedDefaultChar);
7448 if (outsize <= 0)
7449 goto error;
7450 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007451 if (pusedDefaultChar && *pusedDefaultChar) {
7452 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007454 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007455
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007457 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007459 if (*outbytes == NULL) {
7460 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007461 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007462 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007464 }
7465 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007466 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 const Py_ssize_t n = PyBytes_Size(*outbytes);
7468 if (outsize > PY_SSIZE_T_MAX - n) {
7469 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007470 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007471 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007473 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7474 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007476 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007477 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007478 }
7479
7480 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007482 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 out, outsize,
7484 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007485 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 if (outsize <= 0)
7487 goto error;
7488 if (pusedDefaultChar && *pusedDefaultChar)
7489 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007490 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007491
Victor Stinner3a50e702011-10-18 21:21:00 +02007492error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007493 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7495 return -2;
7496 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007497 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007498}
7499
Victor Stinner3a50e702011-10-18 21:21:00 +02007500/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007501 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007502 * error handler.
7503 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007504 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 * -1 on other error.
7506 */
7507static int
7508encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007509 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007510 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007511{
Victor Stinner3a50e702011-10-18 21:21:00 +02007512 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007513 Py_ssize_t pos = unicode_offset;
7514 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007515 /* Ideally, we should get reason from FormatMessage. This is the Windows
7516 2000 English version of the message. */
7517 const char *reason = "invalid character";
7518 /* 4=maximum length of a UTF-8 sequence */
7519 char buffer[4];
7520 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7521 Py_ssize_t outsize;
7522 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007523 PyObject *errorHandler = NULL;
7524 PyObject *exc = NULL;
7525 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007526 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007527 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007528 PyObject *rep;
7529 int ret = -1;
7530
7531 assert(insize > 0);
7532
7533 encoding = code_page_name(code_page, &encoding_obj);
7534 if (encoding == NULL)
7535 return -1;
7536
7537 if (errors == NULL || strcmp(errors, "strict") == 0) {
7538 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7539 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007540 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007541 if (exc != NULL) {
7542 PyCodec_StrictErrors(exc);
7543 Py_DECREF(exc);
7544 }
7545 Py_XDECREF(encoding_obj);
7546 return -1;
7547 }
7548
7549 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7550 pusedDefaultChar = &usedDefaultChar;
7551 else
7552 pusedDefaultChar = NULL;
7553
7554 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7555 PyErr_NoMemory();
7556 goto error;
7557 }
7558 outsize = insize * Py_ARRAY_LENGTH(buffer);
7559
7560 if (*outbytes == NULL) {
7561 /* Create string object */
7562 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7563 if (*outbytes == NULL)
7564 goto error;
7565 out = PyBytes_AS_STRING(*outbytes);
7566 }
7567 else {
7568 /* Extend string object */
7569 Py_ssize_t n = PyBytes_Size(*outbytes);
7570 if (n > PY_SSIZE_T_MAX - outsize) {
7571 PyErr_NoMemory();
7572 goto error;
7573 }
7574 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7575 goto error;
7576 out = PyBytes_AS_STRING(*outbytes) + n;
7577 }
7578
7579 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007580 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007581 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007582 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7583 wchar_t chars[2];
7584 int charsize;
7585 if (ch < 0x10000) {
7586 chars[0] = (wchar_t)ch;
7587 charsize = 1;
7588 }
7589 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007590 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7591 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007592 charsize = 2;
7593 }
7594
Victor Stinner3a50e702011-10-18 21:21:00 +02007595 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007596 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007597 buffer, Py_ARRAY_LENGTH(buffer),
7598 NULL, pusedDefaultChar);
7599 if (outsize > 0) {
7600 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7601 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007602 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007603 memcpy(out, buffer, outsize);
7604 out += outsize;
7605 continue;
7606 }
7607 }
7608 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7609 PyErr_SetFromWindowsErr(0);
7610 goto error;
7611 }
7612
Victor Stinner3a50e702011-10-18 21:21:00 +02007613 rep = unicode_encode_call_errorhandler(
7614 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007615 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007616 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007617 if (rep == NULL)
7618 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007619 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007620
7621 if (PyBytes_Check(rep)) {
7622 outsize = PyBytes_GET_SIZE(rep);
7623 if (outsize != 1) {
7624 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7625 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7626 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7627 Py_DECREF(rep);
7628 goto error;
7629 }
7630 out = PyBytes_AS_STRING(*outbytes) + offset;
7631 }
7632 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7633 out += outsize;
7634 }
7635 else {
7636 Py_ssize_t i;
7637 enum PyUnicode_Kind kind;
7638 void *data;
7639
Benjamin Petersonbac79492012-01-14 13:34:47 -05007640 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007641 Py_DECREF(rep);
7642 goto error;
7643 }
7644
7645 outsize = PyUnicode_GET_LENGTH(rep);
7646 if (outsize != 1) {
7647 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7648 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7649 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7650 Py_DECREF(rep);
7651 goto error;
7652 }
7653 out = PyBytes_AS_STRING(*outbytes) + offset;
7654 }
7655 kind = PyUnicode_KIND(rep);
7656 data = PyUnicode_DATA(rep);
7657 for (i=0; i < outsize; i++) {
7658 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7659 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007660 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007661 encoding, unicode,
7662 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007663 "unable to encode error handler result to ASCII");
7664 Py_DECREF(rep);
7665 goto error;
7666 }
7667 *out = (unsigned char)ch;
7668 out++;
7669 }
7670 }
7671 Py_DECREF(rep);
7672 }
7673 /* write a NUL byte */
7674 *out = 0;
7675 outsize = out - PyBytes_AS_STRING(*outbytes);
7676 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7677 if (_PyBytes_Resize(outbytes, outsize) < 0)
7678 goto error;
7679 ret = 0;
7680
7681error:
7682 Py_XDECREF(encoding_obj);
7683 Py_XDECREF(errorHandler);
7684 Py_XDECREF(exc);
7685 return ret;
7686}
7687
Victor Stinner3a50e702011-10-18 21:21:00 +02007688static PyObject *
7689encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007690 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007691 const char *errors)
7692{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007693 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007694 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007695 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007696 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007697
Victor Stinner29dacf22015-01-26 16:41:32 +01007698 if (!PyUnicode_Check(unicode)) {
7699 PyErr_BadArgument();
7700 return NULL;
7701 }
7702
Benjamin Petersonbac79492012-01-14 13:34:47 -05007703 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007704 return NULL;
7705 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007706
Victor Stinner3a50e702011-10-18 21:21:00 +02007707 if (code_page < 0) {
7708 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7709 return NULL;
7710 }
7711
Martin v. Löwis3d325192011-11-04 18:23:06 +01007712 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007713 return PyBytes_FromStringAndSize(NULL, 0);
7714
Victor Stinner7581cef2011-11-03 22:32:33 +01007715 offset = 0;
7716 do
7717 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007718#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007719 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007720 chunks. */
7721 if (len > INT_MAX/2) {
7722 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007723 done = 0;
7724 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007725 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007726#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007727 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007728 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007729 done = 1;
7730 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007731
Victor Stinner76a31a62011-11-04 00:05:13 +01007732 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007733 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007734 errors);
7735 if (ret == -2)
7736 ret = encode_code_page_errors(code_page, &outbytes,
7737 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007738 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007739 if (ret < 0) {
7740 Py_XDECREF(outbytes);
7741 return NULL;
7742 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007743
Victor Stinner7581cef2011-11-03 22:32:33 +01007744 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007745 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007746 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007747
Victor Stinner3a50e702011-10-18 21:21:00 +02007748 return outbytes;
7749}
7750
7751PyObject *
7752PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7753 Py_ssize_t size,
7754 const char *errors)
7755{
Victor Stinner7581cef2011-11-03 22:32:33 +01007756 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007757 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007758 if (unicode == NULL)
7759 return NULL;
7760 res = encode_code_page(CP_ACP, unicode, errors);
7761 Py_DECREF(unicode);
7762 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007763}
7764
7765PyObject *
7766PyUnicode_EncodeCodePage(int code_page,
7767 PyObject *unicode,
7768 const char *errors)
7769{
Victor Stinner7581cef2011-11-03 22:32:33 +01007770 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007771}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007772
Alexander Belopolsky40018472011-02-26 01:02:56 +00007773PyObject *
7774PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007775{
Victor Stinner7581cef2011-11-03 22:32:33 +01007776 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007777}
7778
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007779#undef NEED_RETRY
7780
Steve Dowercc16be82016-09-08 10:35:16 -07007781#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007782
Guido van Rossumd57fd912000-03-10 22:53:23 +00007783/* --- Character Mapping Codec -------------------------------------------- */
7784
Victor Stinnerfb161b12013-04-18 01:44:27 +02007785static int
7786charmap_decode_string(const char *s,
7787 Py_ssize_t size,
7788 PyObject *mapping,
7789 const char *errors,
7790 _PyUnicodeWriter *writer)
7791{
7792 const char *starts = s;
7793 const char *e;
7794 Py_ssize_t startinpos, endinpos;
7795 PyObject *errorHandler = NULL, *exc = NULL;
7796 Py_ssize_t maplen;
7797 enum PyUnicode_Kind mapkind;
7798 void *mapdata;
7799 Py_UCS4 x;
7800 unsigned char ch;
7801
7802 if (PyUnicode_READY(mapping) == -1)
7803 return -1;
7804
7805 maplen = PyUnicode_GET_LENGTH(mapping);
7806 mapdata = PyUnicode_DATA(mapping);
7807 mapkind = PyUnicode_KIND(mapping);
7808
7809 e = s + size;
7810
7811 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7812 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7813 * is disabled in encoding aliases, latin1 is preferred because
7814 * its implementation is faster. */
7815 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7816 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7817 Py_UCS4 maxchar = writer->maxchar;
7818
7819 assert (writer->kind == PyUnicode_1BYTE_KIND);
7820 while (s < e) {
7821 ch = *s;
7822 x = mapdata_ucs1[ch];
7823 if (x > maxchar) {
7824 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7825 goto onError;
7826 maxchar = writer->maxchar;
7827 outdata = (Py_UCS1 *)writer->data;
7828 }
7829 outdata[writer->pos] = x;
7830 writer->pos++;
7831 ++s;
7832 }
7833 return 0;
7834 }
7835
7836 while (s < e) {
7837 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7838 enum PyUnicode_Kind outkind = writer->kind;
7839 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7840 if (outkind == PyUnicode_1BYTE_KIND) {
7841 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7842 Py_UCS4 maxchar = writer->maxchar;
7843 while (s < e) {
7844 ch = *s;
7845 x = mapdata_ucs2[ch];
7846 if (x > maxchar)
7847 goto Error;
7848 outdata[writer->pos] = x;
7849 writer->pos++;
7850 ++s;
7851 }
7852 break;
7853 }
7854 else if (outkind == PyUnicode_2BYTE_KIND) {
7855 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7856 while (s < e) {
7857 ch = *s;
7858 x = mapdata_ucs2[ch];
7859 if (x == 0xFFFE)
7860 goto Error;
7861 outdata[writer->pos] = x;
7862 writer->pos++;
7863 ++s;
7864 }
7865 break;
7866 }
7867 }
7868 ch = *s;
7869
7870 if (ch < maplen)
7871 x = PyUnicode_READ(mapkind, mapdata, ch);
7872 else
7873 x = 0xfffe; /* invalid value */
7874Error:
7875 if (x == 0xfffe)
7876 {
7877 /* undefined mapping */
7878 startinpos = s-starts;
7879 endinpos = startinpos+1;
7880 if (unicode_decode_call_errorhandler_writer(
7881 errors, &errorHandler,
7882 "charmap", "character maps to <undefined>",
7883 &starts, &e, &startinpos, &endinpos, &exc, &s,
7884 writer)) {
7885 goto onError;
7886 }
7887 continue;
7888 }
7889
7890 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7891 goto onError;
7892 ++s;
7893 }
7894 Py_XDECREF(errorHandler);
7895 Py_XDECREF(exc);
7896 return 0;
7897
7898onError:
7899 Py_XDECREF(errorHandler);
7900 Py_XDECREF(exc);
7901 return -1;
7902}
7903
7904static int
7905charmap_decode_mapping(const char *s,
7906 Py_ssize_t size,
7907 PyObject *mapping,
7908 const char *errors,
7909 _PyUnicodeWriter *writer)
7910{
7911 const char *starts = s;
7912 const char *e;
7913 Py_ssize_t startinpos, endinpos;
7914 PyObject *errorHandler = NULL, *exc = NULL;
7915 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007916 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007917
7918 e = s + size;
7919
7920 while (s < e) {
7921 ch = *s;
7922
7923 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7924 key = PyLong_FromLong((long)ch);
7925 if (key == NULL)
7926 goto onError;
7927
7928 item = PyObject_GetItem(mapping, key);
7929 Py_DECREF(key);
7930 if (item == NULL) {
7931 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7932 /* No mapping found means: mapping is undefined. */
7933 PyErr_Clear();
7934 goto Undefined;
7935 } else
7936 goto onError;
7937 }
7938
7939 /* Apply mapping */
7940 if (item == Py_None)
7941 goto Undefined;
7942 if (PyLong_Check(item)) {
7943 long value = PyLong_AS_LONG(item);
7944 if (value == 0xFFFE)
7945 goto Undefined;
7946 if (value < 0 || value > MAX_UNICODE) {
7947 PyErr_Format(PyExc_TypeError,
7948 "character mapping must be in range(0x%lx)",
7949 (unsigned long)MAX_UNICODE + 1);
7950 goto onError;
7951 }
7952
7953 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7954 goto onError;
7955 }
7956 else if (PyUnicode_Check(item)) {
7957 if (PyUnicode_READY(item) == -1)
7958 goto onError;
7959 if (PyUnicode_GET_LENGTH(item) == 1) {
7960 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7961 if (value == 0xFFFE)
7962 goto Undefined;
7963 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7964 goto onError;
7965 }
7966 else {
7967 writer->overallocate = 1;
7968 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7969 goto onError;
7970 }
7971 }
7972 else {
7973 /* wrong return value */
7974 PyErr_SetString(PyExc_TypeError,
7975 "character mapping must return integer, None or str");
7976 goto onError;
7977 }
7978 Py_CLEAR(item);
7979 ++s;
7980 continue;
7981
7982Undefined:
7983 /* undefined mapping */
7984 Py_CLEAR(item);
7985 startinpos = s-starts;
7986 endinpos = startinpos+1;
7987 if (unicode_decode_call_errorhandler_writer(
7988 errors, &errorHandler,
7989 "charmap", "character maps to <undefined>",
7990 &starts, &e, &startinpos, &endinpos, &exc, &s,
7991 writer)) {
7992 goto onError;
7993 }
7994 }
7995 Py_XDECREF(errorHandler);
7996 Py_XDECREF(exc);
7997 return 0;
7998
7999onError:
8000 Py_XDECREF(item);
8001 Py_XDECREF(errorHandler);
8002 Py_XDECREF(exc);
8003 return -1;
8004}
8005
Alexander Belopolsky40018472011-02-26 01:02:56 +00008006PyObject *
8007PyUnicode_DecodeCharmap(const char *s,
8008 Py_ssize_t size,
8009 PyObject *mapping,
8010 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008011{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008012 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008013
Guido van Rossumd57fd912000-03-10 22:53:23 +00008014 /* Default to Latin-1 */
8015 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008017
Guido van Rossumd57fd912000-03-10 22:53:23 +00008018 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008019 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008020 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008021 writer.min_length = size;
8022 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008023 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008024
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008025 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008026 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8027 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008028 }
8029 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008030 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8031 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008032 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008033 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008034
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008036 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008037 return NULL;
8038}
8039
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008040/* Charmap encoding: the lookup table */
8041
Alexander Belopolsky40018472011-02-26 01:02:56 +00008042struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008043 PyObject_HEAD
8044 unsigned char level1[32];
8045 int count2, count3;
8046 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008047};
8048
8049static PyObject*
8050encoding_map_size(PyObject *obj, PyObject* args)
8051{
8052 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008053 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008054 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055}
8056
8057static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008058 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 PyDoc_STR("Return the size (in bytes) of this object") },
8060 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008061};
8062
8063static void
8064encoding_map_dealloc(PyObject* o)
8065{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008066 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008067}
8068
8069static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008070 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 "EncodingMap", /*tp_name*/
8072 sizeof(struct encoding_map), /*tp_basicsize*/
8073 0, /*tp_itemsize*/
8074 /* methods */
8075 encoding_map_dealloc, /*tp_dealloc*/
8076 0, /*tp_print*/
8077 0, /*tp_getattr*/
8078 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008079 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 0, /*tp_repr*/
8081 0, /*tp_as_number*/
8082 0, /*tp_as_sequence*/
8083 0, /*tp_as_mapping*/
8084 0, /*tp_hash*/
8085 0, /*tp_call*/
8086 0, /*tp_str*/
8087 0, /*tp_getattro*/
8088 0, /*tp_setattro*/
8089 0, /*tp_as_buffer*/
8090 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8091 0, /*tp_doc*/
8092 0, /*tp_traverse*/
8093 0, /*tp_clear*/
8094 0, /*tp_richcompare*/
8095 0, /*tp_weaklistoffset*/
8096 0, /*tp_iter*/
8097 0, /*tp_iternext*/
8098 encoding_map_methods, /*tp_methods*/
8099 0, /*tp_members*/
8100 0, /*tp_getset*/
8101 0, /*tp_base*/
8102 0, /*tp_dict*/
8103 0, /*tp_descr_get*/
8104 0, /*tp_descr_set*/
8105 0, /*tp_dictoffset*/
8106 0, /*tp_init*/
8107 0, /*tp_alloc*/
8108 0, /*tp_new*/
8109 0, /*tp_free*/
8110 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111};
8112
8113PyObject*
8114PyUnicode_BuildEncodingMap(PyObject* string)
8115{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008116 PyObject *result;
8117 struct encoding_map *mresult;
8118 int i;
8119 int need_dict = 0;
8120 unsigned char level1[32];
8121 unsigned char level2[512];
8122 unsigned char *mlevel1, *mlevel2, *mlevel3;
8123 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008124 int kind;
8125 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008126 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008127 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008129 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 PyErr_BadArgument();
8131 return NULL;
8132 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008133 kind = PyUnicode_KIND(string);
8134 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008135 length = PyUnicode_GET_LENGTH(string);
8136 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008137 memset(level1, 0xFF, sizeof level1);
8138 memset(level2, 0xFF, sizeof level2);
8139
8140 /* If there isn't a one-to-one mapping of NULL to \0,
8141 or if there are non-BMP characters, we need to use
8142 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008143 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008145 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008146 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008147 ch = PyUnicode_READ(kind, data, i);
8148 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008149 need_dict = 1;
8150 break;
8151 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008152 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008153 /* unmapped character */
8154 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008155 l1 = ch >> 11;
8156 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008157 if (level1[l1] == 0xFF)
8158 level1[l1] = count2++;
8159 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008160 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008161 }
8162
8163 if (count2 >= 0xFF || count3 >= 0xFF)
8164 need_dict = 1;
8165
8166 if (need_dict) {
8167 PyObject *result = PyDict_New();
8168 PyObject *key, *value;
8169 if (!result)
8170 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008171 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008172 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008173 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008174 if (!key || !value)
8175 goto failed1;
8176 if (PyDict_SetItem(result, key, value) == -1)
8177 goto failed1;
8178 Py_DECREF(key);
8179 Py_DECREF(value);
8180 }
8181 return result;
8182 failed1:
8183 Py_XDECREF(key);
8184 Py_XDECREF(value);
8185 Py_DECREF(result);
8186 return NULL;
8187 }
8188
8189 /* Create a three-level trie */
8190 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8191 16*count2 + 128*count3 - 1);
8192 if (!result)
8193 return PyErr_NoMemory();
8194 PyObject_Init(result, &EncodingMapType);
8195 mresult = (struct encoding_map*)result;
8196 mresult->count2 = count2;
8197 mresult->count3 = count3;
8198 mlevel1 = mresult->level1;
8199 mlevel2 = mresult->level23;
8200 mlevel3 = mresult->level23 + 16*count2;
8201 memcpy(mlevel1, level1, 32);
8202 memset(mlevel2, 0xFF, 16*count2);
8203 memset(mlevel3, 0, 128*count3);
8204 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008205 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008206 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008207 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8208 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008209 /* unmapped character */
8210 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008211 o1 = ch>>11;
8212 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008213 i2 = 16*mlevel1[o1] + o2;
8214 if (mlevel2[i2] == 0xFF)
8215 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008216 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008217 i3 = 128*mlevel2[i2] + o3;
8218 mlevel3[i3] = i;
8219 }
8220 return result;
8221}
8222
8223static int
Victor Stinner22168992011-11-20 17:09:18 +01008224encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008225{
8226 struct encoding_map *map = (struct encoding_map*)mapping;
8227 int l1 = c>>11;
8228 int l2 = (c>>7) & 0xF;
8229 int l3 = c & 0x7F;
8230 int i;
8231
Victor Stinner22168992011-11-20 17:09:18 +01008232 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008234 if (c == 0)
8235 return 0;
8236 /* level 1*/
8237 i = map->level1[l1];
8238 if (i == 0xFF) {
8239 return -1;
8240 }
8241 /* level 2*/
8242 i = map->level23[16*i+l2];
8243 if (i == 0xFF) {
8244 return -1;
8245 }
8246 /* level 3 */
8247 i = map->level23[16*map->count2 + 128*i + l3];
8248 if (i == 0) {
8249 return -1;
8250 }
8251 return i;
8252}
8253
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008254/* Lookup the character ch in the mapping. If the character
8255 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008256 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008257static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008258charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008259{
Christian Heimes217cfd12007-12-02 14:31:20 +00008260 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 PyObject *x;
8262
8263 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 x = PyObject_GetItem(mapping, w);
8266 Py_DECREF(w);
8267 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008268 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8269 /* No mapping found means: mapping is undefined. */
8270 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008271 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 } else
8273 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008274 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008275 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008277 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 long value = PyLong_AS_LONG(x);
8279 if (value < 0 || value > 255) {
8280 PyErr_SetString(PyExc_TypeError,
8281 "character mapping must be in range(256)");
8282 Py_DECREF(x);
8283 return NULL;
8284 }
8285 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008286 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008287 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008289 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008290 /* wrong return value */
8291 PyErr_Format(PyExc_TypeError,
8292 "character mapping must return integer, bytes or None, not %.400s",
8293 x->ob_type->tp_name);
8294 Py_DECREF(x);
8295 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008296 }
8297}
8298
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008299static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008300charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008301{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008302 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8303 /* exponentially overallocate to minimize reallocations */
8304 if (requiredsize < 2*outsize)
8305 requiredsize = 2*outsize;
8306 if (_PyBytes_Resize(outobj, requiredsize))
8307 return -1;
8308 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008309}
8310
Benjamin Peterson14339b62009-01-31 16:36:08 +00008311typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008313} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008315 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 space is available. Return a new reference to the object that
8317 was put in the output buffer, or Py_None, if the mapping was undefined
8318 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008319 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008320static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008321charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008322 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008324 PyObject *rep;
8325 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008326 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008327
Christian Heimes90aa7642007-12-19 02:45:37 +00008328 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008329 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008331 if (res == -1)
8332 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 if (outsize<requiredsize)
8334 if (charmapencode_resize(outobj, outpos, requiredsize))
8335 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008336 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 outstart[(*outpos)++] = (char)res;
8338 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008339 }
8340
8341 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008344 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 Py_DECREF(rep);
8346 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008347 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008348 if (PyLong_Check(rep)) {
8349 Py_ssize_t requiredsize = *outpos+1;
8350 if (outsize<requiredsize)
8351 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8352 Py_DECREF(rep);
8353 return enc_EXCEPTION;
8354 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008355 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008357 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 else {
8359 const char *repchars = PyBytes_AS_STRING(rep);
8360 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8361 Py_ssize_t requiredsize = *outpos+repsize;
8362 if (outsize<requiredsize)
8363 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8364 Py_DECREF(rep);
8365 return enc_EXCEPTION;
8366 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008367 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 memcpy(outstart + *outpos, repchars, repsize);
8369 *outpos += repsize;
8370 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008372 Py_DECREF(rep);
8373 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374}
8375
8376/* handle an error in PyUnicode_EncodeCharmap
8377 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008378static int
8379charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008380 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008382 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008383 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384{
8385 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008386 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008387 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008388 enum PyUnicode_Kind kind;
8389 void *data;
8390 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008392 Py_ssize_t collstartpos = *inpos;
8393 Py_ssize_t collendpos = *inpos+1;
8394 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008395 const char *encoding = "charmap";
8396 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008397 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008398 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008399 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008400
Benjamin Petersonbac79492012-01-14 13:34:47 -05008401 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008402 return -1;
8403 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404 /* find all unencodable characters */
8405 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008406 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008407 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008408 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008409 val = encoding_map_lookup(ch, mapping);
8410 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 break;
8412 ++collendpos;
8413 continue;
8414 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008415
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008416 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8417 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 if (rep==NULL)
8419 return -1;
8420 else if (rep!=Py_None) {
8421 Py_DECREF(rep);
8422 break;
8423 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008424 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008426 }
8427 /* cache callback name lookup
8428 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008429 if (*error_handler == _Py_ERROR_UNKNOWN)
8430 *error_handler = get_error_handler(errors);
8431
8432 switch (*error_handler) {
8433 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008434 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008435 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008436
8437 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008438 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 x = charmapencode_output('?', mapping, res, respos);
8440 if (x==enc_EXCEPTION) {
8441 return -1;
8442 }
8443 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008444 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 return -1;
8446 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008447 }
8448 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008449 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008450 *inpos = collendpos;
8451 break;
Victor Stinner50149202015-09-22 00:26:54 +02008452
8453 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008454 /* generate replacement (temporarily (mis)uses p) */
8455 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 char buffer[2+29+1+1];
8457 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008458 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 for (cp = buffer; *cp; ++cp) {
8460 x = charmapencode_output(*cp, mapping, res, respos);
8461 if (x==enc_EXCEPTION)
8462 return -1;
8463 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008464 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 return -1;
8466 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008467 }
8468 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008469 *inpos = collendpos;
8470 break;
Victor Stinner50149202015-09-22 00:26:54 +02008471
Benjamin Peterson14339b62009-01-31 16:36:08 +00008472 default:
Victor Stinner50149202015-09-22 00:26:54 +02008473 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008474 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008476 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008478 if (PyBytes_Check(repunicode)) {
8479 /* Directly copy bytes result to output. */
8480 Py_ssize_t outsize = PyBytes_Size(*res);
8481 Py_ssize_t requiredsize;
8482 repsize = PyBytes_Size(repunicode);
8483 requiredsize = *respos + repsize;
8484 if (requiredsize > outsize)
8485 /* Make room for all additional bytes. */
8486 if (charmapencode_resize(res, respos, requiredsize)) {
8487 Py_DECREF(repunicode);
8488 return -1;
8489 }
8490 memcpy(PyBytes_AsString(*res) + *respos,
8491 PyBytes_AsString(repunicode), repsize);
8492 *respos += repsize;
8493 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008494 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008495 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008496 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008497 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008498 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008499 Py_DECREF(repunicode);
8500 return -1;
8501 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008502 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008503 data = PyUnicode_DATA(repunicode);
8504 kind = PyUnicode_KIND(repunicode);
8505 for (index = 0; index < repsize; index++) {
8506 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8507 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008509 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 return -1;
8511 }
8512 else if (x==enc_FAILED) {
8513 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008514 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 return -1;
8516 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008517 }
8518 *inpos = newpos;
8519 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 }
8521 return 0;
8522}
8523
Alexander Belopolsky40018472011-02-26 01:02:56 +00008524PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008525_PyUnicode_EncodeCharmap(PyObject *unicode,
8526 PyObject *mapping,
8527 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008528{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529 /* output object */
8530 PyObject *res = NULL;
8531 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008532 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008533 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008534 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008535 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008536 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008538 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008539 void *data;
8540 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008541
Benjamin Petersonbac79492012-01-14 13:34:47 -05008542 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008543 return NULL;
8544 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008545 data = PyUnicode_DATA(unicode);
8546 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008547
Guido van Rossumd57fd912000-03-10 22:53:23 +00008548 /* Default to Latin-1 */
8549 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008550 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008551
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552 /* allocate enough for a simple encoding without
8553 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008554 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008555 if (res == NULL)
8556 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008557 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008561 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008563 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 if (x==enc_EXCEPTION) /* error */
8565 goto onError;
8566 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008567 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008568 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008569 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 &res, &respos)) {
8571 goto onError;
8572 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008573 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008574 else
8575 /* done with this character => adjust input position */
8576 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008577 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008578
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008579 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008580 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008581 if (_PyBytes_Resize(&res, respos) < 0)
8582 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008583
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008584 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008585 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008586 return res;
8587
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008589 Py_XDECREF(res);
8590 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008591 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592 return NULL;
8593}
8594
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008595/* Deprecated */
8596PyObject *
8597PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8598 Py_ssize_t size,
8599 PyObject *mapping,
8600 const char *errors)
8601{
8602 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008603 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008604 if (unicode == NULL)
8605 return NULL;
8606 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8607 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008608 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008609}
8610
Alexander Belopolsky40018472011-02-26 01:02:56 +00008611PyObject *
8612PyUnicode_AsCharmapString(PyObject *unicode,
8613 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008614{
8615 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 PyErr_BadArgument();
8617 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008618 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008619 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008620}
8621
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008623static void
8624make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008626 Py_ssize_t startpos, Py_ssize_t endpos,
8627 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008628{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008629 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008630 *exceptionObject = _PyUnicodeTranslateError_Create(
8631 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008632 }
8633 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8635 goto onError;
8636 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8637 goto onError;
8638 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8639 goto onError;
8640 return;
8641 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008642 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008643 }
8644}
8645
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008646/* error handling callback helper:
8647 build arguments, call the callback and check the arguments,
8648 put the result into newpos and return the replacement string, which
8649 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008650static PyObject *
8651unicode_translate_call_errorhandler(const char *errors,
8652 PyObject **errorHandler,
8653 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008654 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008655 Py_ssize_t startpos, Py_ssize_t endpos,
8656 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008657{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008658 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008660 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661 PyObject *restuple;
8662 PyObject *resunicode;
8663
8664 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008665 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008666 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008668 }
8669
8670 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008672 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008675 restuple = PyObject_CallFunctionObjArgs(
8676 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008680 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008681 Py_DECREF(restuple);
8682 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008684 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008685 &resunicode, &i_newpos)) {
8686 Py_DECREF(restuple);
8687 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008689 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008690 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008691 else
8692 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008694 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 Py_DECREF(restuple);
8696 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008697 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008698 Py_INCREF(resunicode);
8699 Py_DECREF(restuple);
8700 return resunicode;
8701}
8702
8703/* Lookup the character ch in the mapping and put the result in result,
8704 which must be decrefed by the caller.
8705 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008706static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008707charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008708{
Christian Heimes217cfd12007-12-02 14:31:20 +00008709 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008710 PyObject *x;
8711
8712 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008714 x = PyObject_GetItem(mapping, w);
8715 Py_DECREF(w);
8716 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8718 /* No mapping found means: use 1:1 mapping. */
8719 PyErr_Clear();
8720 *result = NULL;
8721 return 0;
8722 } else
8723 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008724 }
8725 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 *result = x;
8727 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008728 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008729 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008731 if (value < 0 || value > MAX_UNICODE) {
8732 PyErr_Format(PyExc_ValueError,
8733 "character mapping must be in range(0x%x)",
8734 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 Py_DECREF(x);
8736 return -1;
8737 }
8738 *result = x;
8739 return 0;
8740 }
8741 else if (PyUnicode_Check(x)) {
8742 *result = x;
8743 return 0;
8744 }
8745 else {
8746 /* wrong return value */
8747 PyErr_SetString(PyExc_TypeError,
8748 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008749 Py_DECREF(x);
8750 return -1;
8751 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008752}
Victor Stinner1194ea02014-04-04 19:37:40 +02008753
8754/* lookup the character, write the result into the writer.
8755 Return 1 if the result was written into the writer, return 0 if the mapping
8756 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008757static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008758charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8759 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008760{
Victor Stinner1194ea02014-04-04 19:37:40 +02008761 PyObject *item;
8762
8763 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008764 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008765
8766 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008768 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008771 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008772 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008773
8774 if (item == Py_None) {
8775 Py_DECREF(item);
8776 return 0;
8777 }
8778
8779 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008780 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8781 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8782 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008783 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8784 Py_DECREF(item);
8785 return -1;
8786 }
8787 Py_DECREF(item);
8788 return 1;
8789 }
8790
8791 if (!PyUnicode_Check(item)) {
8792 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008793 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008794 }
8795
8796 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8797 Py_DECREF(item);
8798 return -1;
8799 }
8800
8801 Py_DECREF(item);
8802 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008803}
8804
Victor Stinner89a76ab2014-04-05 11:44:04 +02008805static int
8806unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8807 Py_UCS1 *translate)
8808{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008809 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008810 int ret = 0;
8811
Victor Stinner89a76ab2014-04-05 11:44:04 +02008812 if (charmaptranslate_lookup(ch, mapping, &item)) {
8813 return -1;
8814 }
8815
8816 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008817 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008818 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008819 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008820 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008821 /* not found => default to 1:1 mapping */
8822 translate[ch] = ch;
8823 return 1;
8824 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008825 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008826 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008827 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8828 used it */
8829 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008830 /* invalid character or character outside ASCII:
8831 skip the fast translate */
8832 goto exit;
8833 }
8834 translate[ch] = (Py_UCS1)replace;
8835 }
8836 else if (PyUnicode_Check(item)) {
8837 Py_UCS4 replace;
8838
8839 if (PyUnicode_READY(item) == -1) {
8840 Py_DECREF(item);
8841 return -1;
8842 }
8843 if (PyUnicode_GET_LENGTH(item) != 1)
8844 goto exit;
8845
8846 replace = PyUnicode_READ_CHAR(item, 0);
8847 if (replace > 127)
8848 goto exit;
8849 translate[ch] = (Py_UCS1)replace;
8850 }
8851 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008852 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008853 goto exit;
8854 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008855 ret = 1;
8856
Benjamin Peterson1365de72014-04-07 20:15:41 -04008857 exit:
8858 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859 return ret;
8860}
8861
8862/* Fast path for ascii => ascii translation. Return 1 if the whole string
8863 was translated into writer, return 0 if the input string was partially
8864 translated into writer, raise an exception and return -1 on error. */
8865static int
8866unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008867 _PyUnicodeWriter *writer, int ignore,
8868 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008869{
Victor Stinner872b2912014-04-05 14:27:07 +02008870 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008871 Py_ssize_t len;
8872 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008873 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008874
Victor Stinner89a76ab2014-04-05 11:44:04 +02008875 len = PyUnicode_GET_LENGTH(input);
8876
Victor Stinner872b2912014-04-05 14:27:07 +02008877 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878
8879 in = PyUnicode_1BYTE_DATA(input);
8880 end = in + len;
8881
8882 assert(PyUnicode_IS_ASCII(writer->buffer));
8883 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8884 out = PyUnicode_1BYTE_DATA(writer->buffer);
8885
Victor Stinner872b2912014-04-05 14:27:07 +02008886 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008887 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008888 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008889 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008890 int translate = unicode_fast_translate_lookup(mapping, ch,
8891 ascii_table);
8892 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008893 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008894 if (translate == 0)
8895 goto exit;
8896 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008897 }
Victor Stinner872b2912014-04-05 14:27:07 +02008898 if (ch2 == 0xfe) {
8899 if (ignore)
8900 continue;
8901 goto exit;
8902 }
8903 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008904 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008905 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008906 }
Victor Stinner872b2912014-04-05 14:27:07 +02008907 res = 1;
8908
8909exit:
8910 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008911 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008912 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008913}
8914
Victor Stinner3222da22015-10-01 22:07:32 +02008915static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008916_PyUnicode_TranslateCharmap(PyObject *input,
8917 PyObject *mapping,
8918 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008919{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008921 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008922 Py_ssize_t size, i;
8923 int kind;
8924 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008925 _PyUnicodeWriter writer;
8926 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008927 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008928 PyObject *errorHandler = NULL;
8929 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008930 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008931 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008932
Guido van Rossumd57fd912000-03-10 22:53:23 +00008933 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008934 PyErr_BadArgument();
8935 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008936 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008937
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008938 if (PyUnicode_READY(input) == -1)
8939 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008940 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008941 kind = PyUnicode_KIND(input);
8942 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008943
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008944 if (size == 0)
8945 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008946
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008947 /* allocate enough for a simple 1:1 translation without
8948 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008949 _PyUnicodeWriter_Init(&writer);
8950 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008951 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008952
Victor Stinner872b2912014-04-05 14:27:07 +02008953 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8954
Victor Stinner33798672016-03-01 21:59:58 +01008955 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008956 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008957 if (PyUnicode_IS_ASCII(input)) {
8958 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8959 if (res < 0) {
8960 _PyUnicodeWriter_Dealloc(&writer);
8961 return NULL;
8962 }
8963 if (res == 1)
8964 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008965 }
Victor Stinner33798672016-03-01 21:59:58 +01008966 else {
8967 i = 0;
8968 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008971 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008972 int translate;
8973 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8974 Py_ssize_t newpos;
8975 /* startpos for collecting untranslatable chars */
8976 Py_ssize_t collstart;
8977 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008978 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008979
Victor Stinner1194ea02014-04-04 19:37:40 +02008980 ch = PyUnicode_READ(kind, data, i);
8981 translate = charmaptranslate_output(ch, mapping, &writer);
8982 if (translate < 0)
8983 goto onError;
8984
8985 if (translate != 0) {
8986 /* it worked => adjust input pointer */
8987 ++i;
8988 continue;
8989 }
8990
8991 /* untranslatable character */
8992 collstart = i;
8993 collend = i+1;
8994
8995 /* find all untranslatable characters */
8996 while (collend < size) {
8997 PyObject *x;
8998 ch = PyUnicode_READ(kind, data, collend);
8999 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009000 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009001 Py_XDECREF(x);
9002 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009003 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009004 ++collend;
9005 }
9006
9007 if (ignore) {
9008 i = collend;
9009 }
9010 else {
9011 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9012 reason, input, &exc,
9013 collstart, collend, &newpos);
9014 if (repunicode == NULL)
9015 goto onError;
9016 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009017 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009018 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009019 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009020 Py_DECREF(repunicode);
9021 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009022 }
9023 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009024 Py_XDECREF(exc);
9025 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009026 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009027
Benjamin Peterson29060642009-01-31 22:14:21 +00009028 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009029 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009030 Py_XDECREF(exc);
9031 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009032 return NULL;
9033}
9034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035/* Deprecated. Use PyUnicode_Translate instead. */
9036PyObject *
9037PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9038 Py_ssize_t size,
9039 PyObject *mapping,
9040 const char *errors)
9041{
Christian Heimes5f520f42012-09-11 14:03:25 +02009042 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009043 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009044 if (!unicode)
9045 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009046 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9047 Py_DECREF(unicode);
9048 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049}
9050
Alexander Belopolsky40018472011-02-26 01:02:56 +00009051PyObject *
9052PyUnicode_Translate(PyObject *str,
9053 PyObject *mapping,
9054 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009055{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009056 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009057 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009058 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009059}
Tim Petersced69f82003-09-16 20:30:58 +00009060
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009061PyObject *
9062_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9063{
9064 if (!PyUnicode_Check(unicode)) {
9065 PyErr_BadInternalCall();
9066 return NULL;
9067 }
9068 if (PyUnicode_READY(unicode) == -1)
9069 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009070 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009071 /* If the string is already ASCII, just return the same string */
9072 Py_INCREF(unicode);
9073 return unicode;
9074 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009075
9076 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9077 PyObject *result = PyUnicode_New(len, 127);
9078 if (result == NULL) {
9079 return NULL;
9080 }
9081
9082 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9083 int kind = PyUnicode_KIND(unicode);
9084 const void *data = PyUnicode_DATA(unicode);
9085 Py_ssize_t i;
9086 for (i = 0; i < len; ++i) {
9087 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9088 if (ch < 127) {
9089 out[i] = ch;
9090 }
9091 else if (Py_UNICODE_ISSPACE(ch)) {
9092 out[i] = ' ';
9093 }
9094 else {
9095 int decimal = Py_UNICODE_TODECIMAL(ch);
9096 if (decimal < 0) {
9097 out[i] = '?';
9098 _PyUnicode_LENGTH(result) = i + 1;
9099 break;
9100 }
9101 out[i] = '0' + decimal;
9102 }
9103 }
9104
9105 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106}
9107
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009108PyObject *
9109PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9110 Py_ssize_t length)
9111{
Victor Stinnerf0124502011-11-21 23:12:56 +01009112 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009113 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009114 Py_UCS4 maxchar;
9115 enum PyUnicode_Kind kind;
9116 void *data;
9117
Victor Stinner99d7ad02012-02-22 13:37:39 +01009118 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009119 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009120 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009121 if (ch > 127) {
9122 int decimal = Py_UNICODE_TODECIMAL(ch);
9123 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009124 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009125 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009126 }
9127 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009128
9129 /* Copy to a new string */
9130 decimal = PyUnicode_New(length, maxchar);
9131 if (decimal == NULL)
9132 return decimal;
9133 kind = PyUnicode_KIND(decimal);
9134 data = PyUnicode_DATA(decimal);
9135 /* Iterate over code points */
9136 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009137 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009138 if (ch > 127) {
9139 int decimal = Py_UNICODE_TODECIMAL(ch);
9140 if (decimal >= 0)
9141 ch = '0' + decimal;
9142 }
9143 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009144 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009145 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009146}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009147/* --- Decimal Encoder ---------------------------------------------------- */
9148
Alexander Belopolsky40018472011-02-26 01:02:56 +00009149int
9150PyUnicode_EncodeDecimal(Py_UNICODE *s,
9151 Py_ssize_t length,
9152 char *output,
9153 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009154{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009155 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009156 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009157 enum PyUnicode_Kind kind;
9158 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009159
9160 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 PyErr_BadArgument();
9162 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009163 }
9164
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009165 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009166 if (unicode == NULL)
9167 return -1;
9168
Victor Stinner42bf7752011-11-21 22:52:58 +01009169 kind = PyUnicode_KIND(unicode);
9170 data = PyUnicode_DATA(unicode);
9171
Victor Stinnerb84d7232011-11-22 01:50:07 +01009172 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009173 PyObject *exc;
9174 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009175 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009176 Py_ssize_t startpos;
9177
9178 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009179
Benjamin Peterson29060642009-01-31 22:14:21 +00009180 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009181 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009182 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009183 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009184 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009185 decimal = Py_UNICODE_TODECIMAL(ch);
9186 if (decimal >= 0) {
9187 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009188 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009189 continue;
9190 }
9191 if (0 < ch && ch < 256) {
9192 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009193 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009194 continue;
9195 }
Victor Stinner6345be92011-11-25 20:09:01 +01009196
Victor Stinner42bf7752011-11-21 22:52:58 +01009197 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009198 exc = NULL;
9199 raise_encode_exception(&exc, "decimal", unicode,
9200 startpos, startpos+1,
9201 "invalid decimal Unicode string");
9202 Py_XDECREF(exc);
9203 Py_DECREF(unicode);
9204 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009205 }
9206 /* 0-terminate the output string */
9207 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009208 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009209 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009210}
9211
Guido van Rossumd57fd912000-03-10 22:53:23 +00009212/* --- Helpers ------------------------------------------------------------ */
9213
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009214/* helper macro to fixup start/end slice values */
9215#define ADJUST_INDICES(start, end, len) \
9216 if (end > len) \
9217 end = len; \
9218 else if (end < 0) { \
9219 end += len; \
9220 if (end < 0) \
9221 end = 0; \
9222 } \
9223 if (start < 0) { \
9224 start += len; \
9225 if (start < 0) \
9226 start = 0; \
9227 }
9228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009230any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009231 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009232 Py_ssize_t end,
9233 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009235 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236 void *buf1, *buf2;
9237 Py_ssize_t len1, len2, result;
9238
9239 kind1 = PyUnicode_KIND(s1);
9240 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009241 if (kind1 < kind2)
9242 return -1;
9243
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244 len1 = PyUnicode_GET_LENGTH(s1);
9245 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009246 ADJUST_INDICES(start, end, len1);
9247 if (end - start < len2)
9248 return -1;
9249
9250 buf1 = PyUnicode_DATA(s1);
9251 buf2 = PyUnicode_DATA(s2);
9252 if (len2 == 1) {
9253 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9254 result = findchar((const char *)buf1 + kind1*start,
9255 kind1, end - start, ch, direction);
9256 if (result == -1)
9257 return -1;
9258 else
9259 return start + result;
9260 }
9261
9262 if (kind2 != kind1) {
9263 buf2 = _PyUnicode_AsKind(s2, kind1);
9264 if (!buf2)
9265 return -2;
9266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009267
Victor Stinner794d5672011-10-10 03:21:36 +02009268 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009269 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009270 case PyUnicode_1BYTE_KIND:
9271 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9272 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9273 else
9274 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9275 break;
9276 case PyUnicode_2BYTE_KIND:
9277 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9278 break;
9279 case PyUnicode_4BYTE_KIND:
9280 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9281 break;
9282 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009283 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009284 }
9285 }
9286 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009287 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009288 case PyUnicode_1BYTE_KIND:
9289 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9290 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9291 else
9292 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9293 break;
9294 case PyUnicode_2BYTE_KIND:
9295 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9296 break;
9297 case PyUnicode_4BYTE_KIND:
9298 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9299 break;
9300 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009301 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009302 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303 }
9304
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009305 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009306 PyMem_Free(buf2);
9307
9308 return result;
9309}
9310
9311Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009312_PyUnicode_InsertThousandsGrouping(
9313 PyObject *unicode, Py_ssize_t index,
9314 Py_ssize_t n_buffer,
9315 void *digits, Py_ssize_t n_digits,
9316 Py_ssize_t min_width,
9317 const char *grouping, PyObject *thousands_sep,
9318 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319{
Victor Stinner41a863c2012-02-24 00:37:51 +01009320 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009321 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009322 Py_ssize_t thousands_sep_len;
9323 Py_ssize_t len;
9324
9325 if (unicode != NULL) {
9326 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009327 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009328 }
9329 else {
9330 kind = PyUnicode_1BYTE_KIND;
9331 data = NULL;
9332 }
9333 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9334 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9335 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9336 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009337 if (thousands_sep_kind < kind) {
9338 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9339 if (!thousands_sep_data)
9340 return -1;
9341 }
9342 else {
9343 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9344 if (!data)
9345 return -1;
9346 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009347 }
9348
Benjamin Petersonead6b532011-12-20 17:23:42 -06009349 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009350 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009351 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009352 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009353 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009354 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009355 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009356 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009357 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009358 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009359 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009360 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009361 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009362 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009363 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009364 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009365 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009366 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009367 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009369 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009370 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009371 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009372 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009373 break;
9374 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009375 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009377 if (unicode != NULL && thousands_sep_kind != kind) {
9378 if (thousands_sep_kind < kind)
9379 PyMem_Free(thousands_sep_data);
9380 else
9381 PyMem_Free(data);
9382 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009383 if (unicode == NULL) {
9384 *maxchar = 127;
9385 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009386 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009387 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009388 }
9389 }
9390 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391}
9392
9393
Alexander Belopolsky40018472011-02-26 01:02:56 +00009394Py_ssize_t
9395PyUnicode_Count(PyObject *str,
9396 PyObject *substr,
9397 Py_ssize_t start,
9398 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009399{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009400 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009401 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009402 void *buf1 = NULL, *buf2 = NULL;
9403 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009404
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009405 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009406 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009407
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009408 kind1 = PyUnicode_KIND(str);
9409 kind2 = PyUnicode_KIND(substr);
9410 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009411 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009412
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009413 len1 = PyUnicode_GET_LENGTH(str);
9414 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009416 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009417 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009418
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009419 buf1 = PyUnicode_DATA(str);
9420 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009421 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009422 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009423 if (!buf2)
9424 goto onError;
9425 }
9426
9427 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009429 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009430 result = asciilib_count(
9431 ((Py_UCS1*)buf1) + start, end - start,
9432 buf2, len2, PY_SSIZE_T_MAX
9433 );
9434 else
9435 result = ucs1lib_count(
9436 ((Py_UCS1*)buf1) + start, end - start,
9437 buf2, len2, PY_SSIZE_T_MAX
9438 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 break;
9440 case PyUnicode_2BYTE_KIND:
9441 result = ucs2lib_count(
9442 ((Py_UCS2*)buf1) + start, end - start,
9443 buf2, len2, PY_SSIZE_T_MAX
9444 );
9445 break;
9446 case PyUnicode_4BYTE_KIND:
9447 result = ucs4lib_count(
9448 ((Py_UCS4*)buf1) + start, end - start,
9449 buf2, len2, PY_SSIZE_T_MAX
9450 );
9451 break;
9452 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009453 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009454 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009455
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009456 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 PyMem_Free(buf2);
9458
Guido van Rossumd57fd912000-03-10 22:53:23 +00009459 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009461 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 PyMem_Free(buf2);
9463 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464}
9465
Alexander Belopolsky40018472011-02-26 01:02:56 +00009466Py_ssize_t
9467PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009468 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009469 Py_ssize_t start,
9470 Py_ssize_t end,
9471 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009473 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009475
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009476 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477}
9478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479Py_ssize_t
9480PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9481 Py_ssize_t start, Py_ssize_t end,
9482 int direction)
9483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009485 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 if (PyUnicode_READY(str) == -1)
9487 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009488 len = PyUnicode_GET_LENGTH(str);
9489 ADJUST_INDICES(start, end, len);
9490 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009491 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009493 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9494 kind, end-start, ch, direction);
9495 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009496 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009497 else
9498 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499}
9500
Alexander Belopolsky40018472011-02-26 01:02:56 +00009501static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009502tailmatch(PyObject *self,
9503 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009504 Py_ssize_t start,
9505 Py_ssize_t end,
9506 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009507{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 int kind_self;
9509 int kind_sub;
9510 void *data_self;
9511 void *data_sub;
9512 Py_ssize_t offset;
9513 Py_ssize_t i;
9514 Py_ssize_t end_sub;
9515
9516 if (PyUnicode_READY(self) == -1 ||
9517 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009518 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009520 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9521 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009522 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009523 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009525 if (PyUnicode_GET_LENGTH(substring) == 0)
9526 return 1;
9527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528 kind_self = PyUnicode_KIND(self);
9529 data_self = PyUnicode_DATA(self);
9530 kind_sub = PyUnicode_KIND(substring);
9531 data_sub = PyUnicode_DATA(substring);
9532 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9533
9534 if (direction > 0)
9535 offset = end;
9536 else
9537 offset = start;
9538
9539 if (PyUnicode_READ(kind_self, data_self, offset) ==
9540 PyUnicode_READ(kind_sub, data_sub, 0) &&
9541 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9542 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9543 /* If both are of the same kind, memcmp is sufficient */
9544 if (kind_self == kind_sub) {
9545 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009546 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547 data_sub,
9548 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009549 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009551 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009552 else {
9553 /* We do not need to compare 0 and len(substring)-1 because
9554 the if statement above ensured already that they are equal
9555 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556 for (i = 1; i < end_sub; ++i) {
9557 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9558 PyUnicode_READ(kind_sub, data_sub, i))
9559 return 0;
9560 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009561 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563 }
9564
9565 return 0;
9566}
9567
Alexander Belopolsky40018472011-02-26 01:02:56 +00009568Py_ssize_t
9569PyUnicode_Tailmatch(PyObject *str,
9570 PyObject *substr,
9571 Py_ssize_t start,
9572 Py_ssize_t end,
9573 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009575 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009576 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009577
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009578 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579}
9580
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009581static PyObject *
9582ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009584 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9585 char *resdata, *data = PyUnicode_DATA(self);
9586 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009587
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009588 res = PyUnicode_New(len, 127);
9589 if (res == NULL)
9590 return NULL;
9591 resdata = PyUnicode_DATA(res);
9592 if (lower)
9593 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009594 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009595 _Py_bytes_upper(resdata, data, len);
9596 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009597}
9598
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009599static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009600handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009601{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009602 Py_ssize_t j;
9603 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009604 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009605 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009606
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009607 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9608
9609 where ! is a negation and \p{xxx} is a character with property xxx.
9610 */
9611 for (j = i - 1; j >= 0; j--) {
9612 c = PyUnicode_READ(kind, data, j);
9613 if (!_PyUnicode_IsCaseIgnorable(c))
9614 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009615 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009616 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9617 if (final_sigma) {
9618 for (j = i + 1; j < length; j++) {
9619 c = PyUnicode_READ(kind, data, j);
9620 if (!_PyUnicode_IsCaseIgnorable(c))
9621 break;
9622 }
9623 final_sigma = j == length || !_PyUnicode_IsCased(c);
9624 }
9625 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626}
9627
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009628static int
9629lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9630 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009632 /* Obscure special case. */
9633 if (c == 0x3A3) {
9634 mapped[0] = handle_capital_sigma(kind, data, length, i);
9635 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009636 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009638}
9639
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009640static Py_ssize_t
9641do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009642{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009643 Py_ssize_t i, k = 0;
9644 int n_res, j;
9645 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009646
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647 c = PyUnicode_READ(kind, data, 0);
9648 n_res = _PyUnicode_ToUpperFull(c, mapped);
9649 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009650 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009651 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009653 for (i = 1; i < length; i++) {
9654 c = PyUnicode_READ(kind, data, i);
9655 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9656 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009657 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009659 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009660 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009662}
9663
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009664static Py_ssize_t
9665do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9666 Py_ssize_t i, k = 0;
9667
9668 for (i = 0; i < length; i++) {
9669 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9670 int n_res, j;
9671 if (Py_UNICODE_ISUPPER(c)) {
9672 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9673 }
9674 else if (Py_UNICODE_ISLOWER(c)) {
9675 n_res = _PyUnicode_ToUpperFull(c, mapped);
9676 }
9677 else {
9678 n_res = 1;
9679 mapped[0] = c;
9680 }
9681 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009682 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009683 res[k++] = mapped[j];
9684 }
9685 }
9686 return k;
9687}
9688
9689static Py_ssize_t
9690do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9691 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009692{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009693 Py_ssize_t i, k = 0;
9694
9695 for (i = 0; i < length; i++) {
9696 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9697 int n_res, j;
9698 if (lower)
9699 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9700 else
9701 n_res = _PyUnicode_ToUpperFull(c, mapped);
9702 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009703 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009704 res[k++] = mapped[j];
9705 }
9706 }
9707 return k;
9708}
9709
9710static Py_ssize_t
9711do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9712{
9713 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9714}
9715
9716static Py_ssize_t
9717do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9718{
9719 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9720}
9721
Benjamin Petersone51757f2012-01-12 21:10:29 -05009722static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009723do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9724{
9725 Py_ssize_t i, k = 0;
9726
9727 for (i = 0; i < length; i++) {
9728 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9729 Py_UCS4 mapped[3];
9730 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9731 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009732 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009733 res[k++] = mapped[j];
9734 }
9735 }
9736 return k;
9737}
9738
9739static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009740do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9741{
9742 Py_ssize_t i, k = 0;
9743 int previous_is_cased;
9744
9745 previous_is_cased = 0;
9746 for (i = 0; i < length; i++) {
9747 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9748 Py_UCS4 mapped[3];
9749 int n_res, j;
9750
9751 if (previous_is_cased)
9752 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9753 else
9754 n_res = _PyUnicode_ToTitleFull(c, mapped);
9755
9756 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009757 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009758 res[k++] = mapped[j];
9759 }
9760
9761 previous_is_cased = _PyUnicode_IsCased(c);
9762 }
9763 return k;
9764}
9765
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009766static PyObject *
9767case_operation(PyObject *self,
9768 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9769{
9770 PyObject *res = NULL;
9771 Py_ssize_t length, newlength = 0;
9772 int kind, outkind;
9773 void *data, *outdata;
9774 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9775
Benjamin Petersoneea48462012-01-16 14:28:50 -05009776 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009777
9778 kind = PyUnicode_KIND(self);
9779 data = PyUnicode_DATA(self);
9780 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009781 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009782 PyErr_SetString(PyExc_OverflowError, "string is too long");
9783 return NULL;
9784 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009785 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009786 if (tmp == NULL)
9787 return PyErr_NoMemory();
9788 newlength = perform(kind, data, length, tmp, &maxchar);
9789 res = PyUnicode_New(newlength, maxchar);
9790 if (res == NULL)
9791 goto leave;
9792 tmpend = tmp + newlength;
9793 outdata = PyUnicode_DATA(res);
9794 outkind = PyUnicode_KIND(res);
9795 switch (outkind) {
9796 case PyUnicode_1BYTE_KIND:
9797 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9798 break;
9799 case PyUnicode_2BYTE_KIND:
9800 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9801 break;
9802 case PyUnicode_4BYTE_KIND:
9803 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9804 break;
9805 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009806 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009807 }
9808 leave:
9809 PyMem_FREE(tmp);
9810 return res;
9811}
9812
Tim Peters8ce9f162004-08-27 01:49:32 +00009813PyObject *
9814PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009815{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009816 PyObject *res;
9817 PyObject *fseq;
9818 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009819 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009820
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009821 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009822 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009823 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009824 }
9825
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009826 /* NOTE: the following code can't call back into Python code,
9827 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009828 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009829
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009830 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009831 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009832 res = _PyUnicode_JoinArray(separator, items, seqlen);
9833 Py_DECREF(fseq);
9834 return res;
9835}
9836
9837PyObject *
9838_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9839{
9840 PyObject *res = NULL; /* the result */
9841 PyObject *sep = NULL;
9842 Py_ssize_t seplen;
9843 PyObject *item;
9844 Py_ssize_t sz, i, res_offset;
9845 Py_UCS4 maxchar;
9846 Py_UCS4 item_maxchar;
9847 int use_memcpy;
9848 unsigned char *res_data = NULL, *sep_data = NULL;
9849 PyObject *last_obj;
9850 unsigned int kind = 0;
9851
Tim Peters05eba1f2004-08-27 21:32:02 +00009852 /* If empty sequence, return u"". */
9853 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009854 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009855 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009856
Tim Peters05eba1f2004-08-27 21:32:02 +00009857 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009858 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009859 if (seqlen == 1) {
9860 if (PyUnicode_CheckExact(items[0])) {
9861 res = items[0];
9862 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009863 return res;
9864 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009865 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009866 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009867 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009868 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009869 /* Set up sep and seplen */
9870 if (separator == NULL) {
9871 /* fall back to a blank space separator */
9872 sep = PyUnicode_FromOrdinal(' ');
9873 if (!sep)
9874 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009875 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009876 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009877 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009878 else {
9879 if (!PyUnicode_Check(separator)) {
9880 PyErr_Format(PyExc_TypeError,
9881 "separator: expected str instance,"
9882 " %.80s found",
9883 Py_TYPE(separator)->tp_name);
9884 goto onError;
9885 }
9886 if (PyUnicode_READY(separator))
9887 goto onError;
9888 sep = separator;
9889 seplen = PyUnicode_GET_LENGTH(separator);
9890 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9891 /* inc refcount to keep this code path symmetric with the
9892 above case of a blank separator */
9893 Py_INCREF(sep);
9894 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009895 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009896 }
9897
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009898 /* There are at least two things to join, or else we have a subclass
9899 * of str in the sequence.
9900 * Do a pre-pass to figure out the total amount of space we'll
9901 * need (sz), and see whether all argument are strings.
9902 */
9903 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009904#ifdef Py_DEBUG
9905 use_memcpy = 0;
9906#else
9907 use_memcpy = 1;
9908#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009909 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009910 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009911 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009912 if (!PyUnicode_Check(item)) {
9913 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009914 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009915 " %.80s found",
9916 i, Py_TYPE(item)->tp_name);
9917 goto onError;
9918 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 if (PyUnicode_READY(item) == -1)
9920 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009921 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009923 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009924 if (i != 0) {
9925 add_sz += seplen;
9926 }
9927 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009928 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009929 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009930 goto onError;
9931 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009932 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009933 if (use_memcpy && last_obj != NULL) {
9934 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9935 use_memcpy = 0;
9936 }
9937 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009938 }
Tim Petersced69f82003-09-16 20:30:58 +00009939
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009941 if (res == NULL)
9942 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009943
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009944 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009945#ifdef Py_DEBUG
9946 use_memcpy = 0;
9947#else
9948 if (use_memcpy) {
9949 res_data = PyUnicode_1BYTE_DATA(res);
9950 kind = PyUnicode_KIND(res);
9951 if (seplen != 0)
9952 sep_data = PyUnicode_1BYTE_DATA(sep);
9953 }
9954#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009955 if (use_memcpy) {
9956 for (i = 0; i < seqlen; ++i) {
9957 Py_ssize_t itemlen;
9958 item = items[i];
9959
9960 /* Copy item, and maybe the separator. */
9961 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009962 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009963 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009964 kind * seplen);
9965 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009966 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009967
9968 itemlen = PyUnicode_GET_LENGTH(item);
9969 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009970 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009971 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009972 kind * itemlen);
9973 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009974 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009975 }
9976 assert(res_data == PyUnicode_1BYTE_DATA(res)
9977 + kind * PyUnicode_GET_LENGTH(res));
9978 }
9979 else {
9980 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9981 Py_ssize_t itemlen;
9982 item = items[i];
9983
9984 /* Copy item, and maybe the separator. */
9985 if (i && seplen != 0) {
9986 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9987 res_offset += seplen;
9988 }
9989
9990 itemlen = PyUnicode_GET_LENGTH(item);
9991 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009992 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009993 res_offset += itemlen;
9994 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009995 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009996 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009997 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010000 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010002
Benjamin Peterson29060642009-01-31 22:14:21 +000010003 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010005 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010006 return NULL;
10007}
10008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009#define FILL(kind, data, value, start, length) \
10010 do { \
10011 Py_ssize_t i_ = 0; \
10012 assert(kind != PyUnicode_WCHAR_KIND); \
10013 switch ((kind)) { \
10014 case PyUnicode_1BYTE_KIND: { \
10015 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010016 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 break; \
10018 } \
10019 case PyUnicode_2BYTE_KIND: { \
10020 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10021 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10022 break; \
10023 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010024 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10026 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10027 break; \
10028 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010029 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010030 } \
10031 } while (0)
10032
Victor Stinnerd3f08822012-05-29 12:57:52 +020010033void
10034_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10035 Py_UCS4 fill_char)
10036{
10037 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10038 const void *data = PyUnicode_DATA(unicode);
10039 assert(PyUnicode_IS_READY(unicode));
10040 assert(unicode_modifiable(unicode));
10041 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10042 assert(start >= 0);
10043 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10044 FILL(kind, data, fill_char, start, length);
10045}
10046
Victor Stinner3fe55312012-01-04 00:33:50 +010010047Py_ssize_t
10048PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10049 Py_UCS4 fill_char)
10050{
10051 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010052
10053 if (!PyUnicode_Check(unicode)) {
10054 PyErr_BadInternalCall();
10055 return -1;
10056 }
10057 if (PyUnicode_READY(unicode) == -1)
10058 return -1;
10059 if (unicode_check_modifiable(unicode))
10060 return -1;
10061
Victor Stinnerd3f08822012-05-29 12:57:52 +020010062 if (start < 0) {
10063 PyErr_SetString(PyExc_IndexError, "string index out of range");
10064 return -1;
10065 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010066 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10067 PyErr_SetString(PyExc_ValueError,
10068 "fill character is bigger than "
10069 "the string maximum character");
10070 return -1;
10071 }
10072
10073 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10074 length = Py_MIN(maxlen, length);
10075 if (length <= 0)
10076 return 0;
10077
Victor Stinnerd3f08822012-05-29 12:57:52 +020010078 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010079 return length;
10080}
10081
Victor Stinner9310abb2011-10-05 00:59:23 +020010082static PyObject *
10083pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010084 Py_ssize_t left,
10085 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010087{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 PyObject *u;
10089 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010090 int kind;
10091 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092
10093 if (left < 0)
10094 left = 0;
10095 if (right < 0)
10096 right = 0;
10097
Victor Stinnerc4b49542011-12-11 22:44:26 +010010098 if (left == 0 && right == 0)
10099 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010101 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10102 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010103 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10104 return NULL;
10105 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010107 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010109 if (!u)
10110 return NULL;
10111
10112 kind = PyUnicode_KIND(u);
10113 data = PyUnicode_DATA(u);
10114 if (left)
10115 FILL(kind, data, fill, 0, left);
10116 if (right)
10117 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010118 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010119 assert(_PyUnicode_CheckConsistency(u, 1));
10120 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010121}
10122
Alexander Belopolsky40018472011-02-26 01:02:56 +000010123PyObject *
10124PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010125{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010126 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010127
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010128 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010129 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010130
Benjamin Petersonead6b532011-12-20 17:23:42 -060010131 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010133 if (PyUnicode_IS_ASCII(string))
10134 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010135 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010136 PyUnicode_GET_LENGTH(string), keepends);
10137 else
10138 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010139 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010140 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 break;
10142 case PyUnicode_2BYTE_KIND:
10143 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010144 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 PyUnicode_GET_LENGTH(string), keepends);
10146 break;
10147 case PyUnicode_4BYTE_KIND:
10148 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010149 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 PyUnicode_GET_LENGTH(string), keepends);
10151 break;
10152 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010153 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010155 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156}
10157
Alexander Belopolsky40018472011-02-26 01:02:56 +000010158static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010159split(PyObject *self,
10160 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010161 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010163 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 void *buf1, *buf2;
10165 Py_ssize_t len1, len2;
10166 PyObject* out;
10167
Guido van Rossumd57fd912000-03-10 22:53:23 +000010168 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010169 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 if (PyUnicode_READY(self) == -1)
10172 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010175 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010177 if (PyUnicode_IS_ASCII(self))
10178 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010179 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010180 PyUnicode_GET_LENGTH(self), maxcount
10181 );
10182 else
10183 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010184 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010185 PyUnicode_GET_LENGTH(self), maxcount
10186 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187 case PyUnicode_2BYTE_KIND:
10188 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010189 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 PyUnicode_GET_LENGTH(self), maxcount
10191 );
10192 case PyUnicode_4BYTE_KIND:
10193 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010194 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 PyUnicode_GET_LENGTH(self), maxcount
10196 );
10197 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010198 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 }
10200
10201 if (PyUnicode_READY(substring) == -1)
10202 return NULL;
10203
10204 kind1 = PyUnicode_KIND(self);
10205 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 len1 = PyUnicode_GET_LENGTH(self);
10207 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010208 if (kind1 < kind2 || len1 < len2) {
10209 out = PyList_New(1);
10210 if (out == NULL)
10211 return NULL;
10212 Py_INCREF(self);
10213 PyList_SET_ITEM(out, 0, self);
10214 return out;
10215 }
10216 buf1 = PyUnicode_DATA(self);
10217 buf2 = PyUnicode_DATA(substring);
10218 if (kind2 != kind1) {
10219 buf2 = _PyUnicode_AsKind(substring, kind1);
10220 if (!buf2)
10221 return NULL;
10222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010224 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010226 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10227 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010228 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010229 else
10230 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010231 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 break;
10233 case PyUnicode_2BYTE_KIND:
10234 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010235 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 break;
10237 case PyUnicode_4BYTE_KIND:
10238 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010239 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 break;
10241 default:
10242 out = NULL;
10243 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010244 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 PyMem_Free(buf2);
10246 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010247}
10248
Alexander Belopolsky40018472011-02-26 01:02:56 +000010249static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010250rsplit(PyObject *self,
10251 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010252 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010253{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010254 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 void *buf1, *buf2;
10256 Py_ssize_t len1, len2;
10257 PyObject* out;
10258
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010259 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010260 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 if (PyUnicode_READY(self) == -1)
10263 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010264
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010266 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010267 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010268 if (PyUnicode_IS_ASCII(self))
10269 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010270 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010271 PyUnicode_GET_LENGTH(self), maxcount
10272 );
10273 else
10274 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010275 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010276 PyUnicode_GET_LENGTH(self), maxcount
10277 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 case PyUnicode_2BYTE_KIND:
10279 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010280 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 PyUnicode_GET_LENGTH(self), maxcount
10282 );
10283 case PyUnicode_4BYTE_KIND:
10284 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010285 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 PyUnicode_GET_LENGTH(self), maxcount
10287 );
10288 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010289 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 }
10291
10292 if (PyUnicode_READY(substring) == -1)
10293 return NULL;
10294
10295 kind1 = PyUnicode_KIND(self);
10296 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 len1 = PyUnicode_GET_LENGTH(self);
10298 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010299 if (kind1 < kind2 || len1 < len2) {
10300 out = PyList_New(1);
10301 if (out == NULL)
10302 return NULL;
10303 Py_INCREF(self);
10304 PyList_SET_ITEM(out, 0, self);
10305 return out;
10306 }
10307 buf1 = PyUnicode_DATA(self);
10308 buf2 = PyUnicode_DATA(substring);
10309 if (kind2 != kind1) {
10310 buf2 = _PyUnicode_AsKind(substring, kind1);
10311 if (!buf2)
10312 return NULL;
10313 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010315 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010317 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10318 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010319 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010320 else
10321 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010322 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 break;
10324 case PyUnicode_2BYTE_KIND:
10325 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010326 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 break;
10328 case PyUnicode_4BYTE_KIND:
10329 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010330 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 break;
10332 default:
10333 out = NULL;
10334 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010335 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 PyMem_Free(buf2);
10337 return out;
10338}
10339
10340static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010341anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10342 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010344 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010346 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10347 return asciilib_find(buf1, len1, buf2, len2, offset);
10348 else
10349 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 case PyUnicode_2BYTE_KIND:
10351 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10352 case PyUnicode_4BYTE_KIND:
10353 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10354 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010355 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356}
10357
10358static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010359anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10360 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010362 switch (kind) {
10363 case PyUnicode_1BYTE_KIND:
10364 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10365 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10366 else
10367 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10368 case PyUnicode_2BYTE_KIND:
10369 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10370 case PyUnicode_4BYTE_KIND:
10371 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10372 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010373 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010374}
10375
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010376static void
10377replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10378 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10379{
10380 int kind = PyUnicode_KIND(u);
10381 void *data = PyUnicode_DATA(u);
10382 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10383 if (kind == PyUnicode_1BYTE_KIND) {
10384 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10385 (Py_UCS1 *)data + len,
10386 u1, u2, maxcount);
10387 }
10388 else if (kind == PyUnicode_2BYTE_KIND) {
10389 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10390 (Py_UCS2 *)data + len,
10391 u1, u2, maxcount);
10392 }
10393 else {
10394 assert(kind == PyUnicode_4BYTE_KIND);
10395 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10396 (Py_UCS4 *)data + len,
10397 u1, u2, maxcount);
10398 }
10399}
10400
Alexander Belopolsky40018472011-02-26 01:02:56 +000010401static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402replace(PyObject *self, PyObject *str1,
10403 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010404{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 PyObject *u;
10406 char *sbuf = PyUnicode_DATA(self);
10407 char *buf1 = PyUnicode_DATA(str1);
10408 char *buf2 = PyUnicode_DATA(str2);
10409 int srelease = 0, release1 = 0, release2 = 0;
10410 int skind = PyUnicode_KIND(self);
10411 int kind1 = PyUnicode_KIND(str1);
10412 int kind2 = PyUnicode_KIND(str2);
10413 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10414 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10415 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010416 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010417 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418
10419 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010420 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010422 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010423
Victor Stinner59de0ee2011-10-07 10:01:28 +020010424 if (str1 == str2)
10425 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426
Victor Stinner49a0a212011-10-12 23:46:10 +020010427 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010428 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10429 if (maxchar < maxchar_str1)
10430 /* substring too wide to be present */
10431 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010432 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10433 /* Replacing str1 with str2 may cause a maxchar reduction in the
10434 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010435 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010436 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010437
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010439 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010441 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010443 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010444 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010445 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010446
Victor Stinner69ed0f42013-04-09 21:48:24 +020010447 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010448 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010449 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010450 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010451 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010453 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010455
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010456 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10457 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010458 }
10459 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 int rkind = skind;
10461 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010462 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 if (kind1 < rkind) {
10465 /* widen substring */
10466 buf1 = _PyUnicode_AsKind(str1, rkind);
10467 if (!buf1) goto error;
10468 release1 = 1;
10469 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010470 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010471 if (i < 0)
10472 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 if (rkind > kind2) {
10474 /* widen replacement */
10475 buf2 = _PyUnicode_AsKind(str2, rkind);
10476 if (!buf2) goto error;
10477 release2 = 1;
10478 }
10479 else if (rkind < kind2) {
10480 /* widen self and buf1 */
10481 rkind = kind2;
10482 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010483 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 sbuf = _PyUnicode_AsKind(self, rkind);
10485 if (!sbuf) goto error;
10486 srelease = 1;
10487 buf1 = _PyUnicode_AsKind(str1, rkind);
10488 if (!buf1) goto error;
10489 release1 = 1;
10490 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010491 u = PyUnicode_New(slen, maxchar);
10492 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010493 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010494 assert(PyUnicode_KIND(u) == rkind);
10495 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010496
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010497 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010498 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010499 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010501 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010503
10504 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010505 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010506 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010507 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010508 if (i == -1)
10509 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010510 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010512 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010514 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010515 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010516 }
10517 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010519 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 int rkind = skind;
10521 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010524 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 buf1 = _PyUnicode_AsKind(str1, rkind);
10526 if (!buf1) goto error;
10527 release1 = 1;
10528 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010529 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010530 if (n == 0)
10531 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010533 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 buf2 = _PyUnicode_AsKind(str2, rkind);
10535 if (!buf2) goto error;
10536 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010538 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010539 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 rkind = kind2;
10541 sbuf = _PyUnicode_AsKind(self, rkind);
10542 if (!sbuf) goto error;
10543 srelease = 1;
10544 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010545 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 buf1 = _PyUnicode_AsKind(str1, rkind);
10547 if (!buf1) goto error;
10548 release1 = 1;
10549 }
10550 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10551 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010552 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 PyErr_SetString(PyExc_OverflowError,
10554 "replace string is too long");
10555 goto error;
10556 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010557 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010558 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010559 _Py_INCREF_UNICODE_EMPTY();
10560 if (!unicode_empty)
10561 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010562 u = unicode_empty;
10563 goto done;
10564 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010565 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 PyErr_SetString(PyExc_OverflowError,
10567 "replace string is too long");
10568 goto error;
10569 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010570 u = PyUnicode_New(new_size, maxchar);
10571 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010573 assert(PyUnicode_KIND(u) == rkind);
10574 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 ires = i = 0;
10576 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010577 while (n-- > 0) {
10578 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010579 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010580 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010581 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010582 if (j == -1)
10583 break;
10584 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010585 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010586 memcpy(res + rkind * ires,
10587 sbuf + rkind * i,
10588 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010590 }
10591 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010593 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010595 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010597 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010599 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010601 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010602 memcpy(res + rkind * ires,
10603 sbuf + rkind * i,
10604 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010605 }
10606 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010607 /* interleave */
10608 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010609 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010611 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010613 if (--n <= 0)
10614 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010615 memcpy(res + rkind * ires,
10616 sbuf + rkind * i,
10617 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 ires++;
10619 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010620 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010621 memcpy(res + rkind * ires,
10622 sbuf + rkind * i,
10623 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010624 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010625 }
10626
10627 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010628 unicode_adjust_maxchar(&u);
10629 if (u == NULL)
10630 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010632
10633 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 if (srelease)
10635 PyMem_FREE(sbuf);
10636 if (release1)
10637 PyMem_FREE(buf1);
10638 if (release2)
10639 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010640 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010642
Benjamin Peterson29060642009-01-31 22:14:21 +000010643 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010644 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 if (srelease)
10646 PyMem_FREE(sbuf);
10647 if (release1)
10648 PyMem_FREE(buf1);
10649 if (release2)
10650 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010651 return unicode_result_unchanged(self);
10652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 error:
10654 if (srelease && sbuf)
10655 PyMem_FREE(sbuf);
10656 if (release1 && buf1)
10657 PyMem_FREE(buf1);
10658 if (release2 && buf2)
10659 PyMem_FREE(buf2);
10660 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661}
10662
10663/* --- Unicode Object Methods --------------------------------------------- */
10664
INADA Naoki3ae20562017-01-16 20:41:20 +090010665/*[clinic input]
10666str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010667
INADA Naoki3ae20562017-01-16 20:41:20 +090010668Return a version of the string where each word is titlecased.
10669
10670More specifically, words start with uppercased characters and all remaining
10671cased characters have lower case.
10672[clinic start generated code]*/
10673
10674static PyObject *
10675unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010676/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010678 if (PyUnicode_READY(self) == -1)
10679 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010680 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010681}
10682
INADA Naoki3ae20562017-01-16 20:41:20 +090010683/*[clinic input]
10684str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685
INADA Naoki3ae20562017-01-16 20:41:20 +090010686Return a capitalized version of the string.
10687
10688More specifically, make the first character have upper case and the rest lower
10689case.
10690[clinic start generated code]*/
10691
10692static PyObject *
10693unicode_capitalize_impl(PyObject *self)
10694/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010695{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010696 if (PyUnicode_READY(self) == -1)
10697 return NULL;
10698 if (PyUnicode_GET_LENGTH(self) == 0)
10699 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010700 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701}
10702
INADA Naoki3ae20562017-01-16 20:41:20 +090010703/*[clinic input]
10704str.casefold as unicode_casefold
10705
10706Return a version of the string suitable for caseless comparisons.
10707[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010708
10709static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010710unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010711/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010712{
10713 if (PyUnicode_READY(self) == -1)
10714 return NULL;
10715 if (PyUnicode_IS_ASCII(self))
10716 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010717 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010718}
10719
10720
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010721/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010722
10723static int
10724convert_uc(PyObject *obj, void *addr)
10725{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010727
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010728 if (!PyUnicode_Check(obj)) {
10729 PyErr_Format(PyExc_TypeError,
10730 "The fill character must be a unicode character, "
10731 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010732 return 0;
10733 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010734 if (PyUnicode_READY(obj) < 0)
10735 return 0;
10736 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010737 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010738 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010739 return 0;
10740 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010741 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010742 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010743}
10744
INADA Naoki3ae20562017-01-16 20:41:20 +090010745/*[clinic input]
10746str.center as unicode_center
10747
10748 width: Py_ssize_t
10749 fillchar: Py_UCS4 = ' '
10750 /
10751
10752Return a centered string of length width.
10753
10754Padding is done using the specified fill character (default is a space).
10755[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756
10757static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010758unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10759/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010761 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762
Benjamin Petersonbac79492012-01-14 13:34:47 -050010763 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764 return NULL;
10765
Victor Stinnerc4b49542011-12-11 22:44:26 +010010766 if (PyUnicode_GET_LENGTH(self) >= width)
10767 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768
Victor Stinnerc4b49542011-12-11 22:44:26 +010010769 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770 left = marg / 2 + (marg & width & 1);
10771
Victor Stinner9310abb2011-10-05 00:59:23 +020010772 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773}
10774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775/* This function assumes that str1 and str2 are readied by the caller. */
10776
Marc-André Lemburge5034372000-08-08 08:04:29 +000010777static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010778unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010779{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010780#define COMPARE(TYPE1, TYPE2) \
10781 do { \
10782 TYPE1* p1 = (TYPE1 *)data1; \
10783 TYPE2* p2 = (TYPE2 *)data2; \
10784 TYPE1* end = p1 + len; \
10785 Py_UCS4 c1, c2; \
10786 for (; p1 != end; p1++, p2++) { \
10787 c1 = *p1; \
10788 c2 = *p2; \
10789 if (c1 != c2) \
10790 return (c1 < c2) ? -1 : 1; \
10791 } \
10792 } \
10793 while (0)
10794
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 int kind1, kind2;
10796 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010797 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 kind1 = PyUnicode_KIND(str1);
10800 kind2 = PyUnicode_KIND(str2);
10801 data1 = PyUnicode_DATA(str1);
10802 data2 = PyUnicode_DATA(str2);
10803 len1 = PyUnicode_GET_LENGTH(str1);
10804 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010805 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010806
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010807 switch(kind1) {
10808 case PyUnicode_1BYTE_KIND:
10809 {
10810 switch(kind2) {
10811 case PyUnicode_1BYTE_KIND:
10812 {
10813 int cmp = memcmp(data1, data2, len);
10814 /* normalize result of memcmp() into the range [-1; 1] */
10815 if (cmp < 0)
10816 return -1;
10817 if (cmp > 0)
10818 return 1;
10819 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010820 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010821 case PyUnicode_2BYTE_KIND:
10822 COMPARE(Py_UCS1, Py_UCS2);
10823 break;
10824 case PyUnicode_4BYTE_KIND:
10825 COMPARE(Py_UCS1, Py_UCS4);
10826 break;
10827 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010828 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010829 }
10830 break;
10831 }
10832 case PyUnicode_2BYTE_KIND:
10833 {
10834 switch(kind2) {
10835 case PyUnicode_1BYTE_KIND:
10836 COMPARE(Py_UCS2, Py_UCS1);
10837 break;
10838 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010839 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010840 COMPARE(Py_UCS2, Py_UCS2);
10841 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010842 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010843 case PyUnicode_4BYTE_KIND:
10844 COMPARE(Py_UCS2, Py_UCS4);
10845 break;
10846 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010847 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010848 }
10849 break;
10850 }
10851 case PyUnicode_4BYTE_KIND:
10852 {
10853 switch(kind2) {
10854 case PyUnicode_1BYTE_KIND:
10855 COMPARE(Py_UCS4, Py_UCS1);
10856 break;
10857 case PyUnicode_2BYTE_KIND:
10858 COMPARE(Py_UCS4, Py_UCS2);
10859 break;
10860 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010861 {
10862#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10863 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10864 /* normalize result of wmemcmp() into the range [-1; 1] */
10865 if (cmp < 0)
10866 return -1;
10867 if (cmp > 0)
10868 return 1;
10869#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010870 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010871#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010872 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010873 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010874 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010875 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010876 }
10877 break;
10878 }
10879 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010880 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010881 }
10882
Victor Stinner770e19e2012-10-04 22:59:45 +020010883 if (len1 == len2)
10884 return 0;
10885 if (len1 < len2)
10886 return -1;
10887 else
10888 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010889
10890#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010891}
10892
Benjamin Peterson621b4302016-09-09 13:54:34 -070010893static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010894unicode_compare_eq(PyObject *str1, PyObject *str2)
10895{
10896 int kind;
10897 void *data1, *data2;
10898 Py_ssize_t len;
10899 int cmp;
10900
Victor Stinnere5567ad2012-10-23 02:48:49 +020010901 len = PyUnicode_GET_LENGTH(str1);
10902 if (PyUnicode_GET_LENGTH(str2) != len)
10903 return 0;
10904 kind = PyUnicode_KIND(str1);
10905 if (PyUnicode_KIND(str2) != kind)
10906 return 0;
10907 data1 = PyUnicode_DATA(str1);
10908 data2 = PyUnicode_DATA(str2);
10909
10910 cmp = memcmp(data1, data2, len * kind);
10911 return (cmp == 0);
10912}
10913
10914
Alexander Belopolsky40018472011-02-26 01:02:56 +000010915int
10916PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10919 if (PyUnicode_READY(left) == -1 ||
10920 PyUnicode_READY(right) == -1)
10921 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010922
10923 /* a string is equal to itself */
10924 if (left == right)
10925 return 0;
10926
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010927 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010929 PyErr_Format(PyExc_TypeError,
10930 "Can't compare %.100s and %.100s",
10931 left->ob_type->tp_name,
10932 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933 return -1;
10934}
10935
Martin v. Löwis5b222132007-06-10 09:51:05 +000010936int
10937PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10938{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010939 Py_ssize_t i;
10940 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010941 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010942 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010943
Victor Stinner910337b2011-10-03 03:20:16 +020010944 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010945 if (!PyUnicode_IS_READY(uni)) {
10946 const wchar_t *ws = _PyUnicode_WSTR(uni);
10947 /* Compare Unicode string and source character set string */
10948 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10949 if (chr != ustr[i])
10950 return (chr < ustr[i]) ? -1 : 1;
10951 }
10952 /* This check keeps Python strings that end in '\0' from comparing equal
10953 to C strings identical up to that point. */
10954 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10955 return 1; /* uni is longer */
10956 if (ustr[i])
10957 return -1; /* str is longer */
10958 return 0;
10959 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010960 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010961 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010962 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010963 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010964 size_t len, len2 = strlen(str);
10965 int cmp;
10966
10967 len = Py_MIN(len1, len2);
10968 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010969 if (cmp != 0) {
10970 if (cmp < 0)
10971 return -1;
10972 else
10973 return 1;
10974 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010975 if (len1 > len2)
10976 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010977 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010978 return -1; /* str is longer */
10979 return 0;
10980 }
10981 else {
10982 void *data = PyUnicode_DATA(uni);
10983 /* Compare Unicode string and source character set string */
10984 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010985 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010986 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10987 /* This check keeps Python strings that end in '\0' from comparing equal
10988 to C strings identical up to that point. */
10989 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10990 return 1; /* uni is longer */
10991 if (str[i])
10992 return -1; /* str is longer */
10993 return 0;
10994 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010995}
10996
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010997static int
10998non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
10999{
11000 size_t i, len;
11001 const wchar_t *p;
11002 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11003 if (strlen(str) != len)
11004 return 0;
11005 p = _PyUnicode_WSTR(unicode);
11006 assert(p);
11007 for (i = 0; i < len; i++) {
11008 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011009 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011010 return 0;
11011 }
11012 return 1;
11013}
11014
11015int
11016_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11017{
11018 size_t len;
11019 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011020 assert(str);
11021#ifndef NDEBUG
11022 for (const char *p = str; *p; p++) {
11023 assert((unsigned char)*p < 128);
11024 }
11025#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011026 if (PyUnicode_READY(unicode) == -1) {
11027 /* Memory error or bad data */
11028 PyErr_Clear();
11029 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11030 }
11031 if (!PyUnicode_IS_ASCII(unicode))
11032 return 0;
11033 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11034 return strlen(str) == len &&
11035 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11036}
11037
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011038int
11039_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11040{
11041 PyObject *right_uni;
11042 Py_hash_t hash;
11043
11044 assert(_PyUnicode_CHECK(left));
11045 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011046#ifndef NDEBUG
11047 for (const char *p = right->string; *p; p++) {
11048 assert((unsigned char)*p < 128);
11049 }
11050#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011051
11052 if (PyUnicode_READY(left) == -1) {
11053 /* memory error or bad data */
11054 PyErr_Clear();
11055 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11056 }
11057
11058 if (!PyUnicode_IS_ASCII(left))
11059 return 0;
11060
11061 right_uni = _PyUnicode_FromId(right); /* borrowed */
11062 if (right_uni == NULL) {
11063 /* memory error or bad data */
11064 PyErr_Clear();
11065 return _PyUnicode_EqualToASCIIString(left, right->string);
11066 }
11067
11068 if (left == right_uni)
11069 return 1;
11070
11071 if (PyUnicode_CHECK_INTERNED(left))
11072 return 0;
11073
11074 assert(_PyUnicode_HASH(right_uni) != 1);
11075 hash = _PyUnicode_HASH(left);
11076 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11077 return 0;
11078
11079 return unicode_compare_eq(left, right_uni);
11080}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011081
Alexander Belopolsky40018472011-02-26 01:02:56 +000011082PyObject *
11083PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011084{
11085 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011086
Victor Stinnere5567ad2012-10-23 02:48:49 +020011087 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11088 Py_RETURN_NOTIMPLEMENTED;
11089
11090 if (PyUnicode_READY(left) == -1 ||
11091 PyUnicode_READY(right) == -1)
11092 return NULL;
11093
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011094 if (left == right) {
11095 switch (op) {
11096 case Py_EQ:
11097 case Py_LE:
11098 case Py_GE:
11099 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011100 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011101 case Py_NE:
11102 case Py_LT:
11103 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011104 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011105 default:
11106 PyErr_BadArgument();
11107 return NULL;
11108 }
11109 }
11110 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011111 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011112 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011113 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011114 }
11115 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011116 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011117 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011118 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011119}
11120
Alexander Belopolsky40018472011-02-26 01:02:56 +000011121int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011122_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11123{
11124 return unicode_eq(aa, bb);
11125}
11126
11127int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011128PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011129{
Victor Stinner77282cb2013-04-14 19:22:47 +020011130 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011131 void *buf1, *buf2;
11132 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011133 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011134
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011135 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011136 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011137 "'in <string>' requires string as left operand, not %.100s",
11138 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011139 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011140 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011141 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011142 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011143 if (ensure_unicode(str) < 0)
11144 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011146 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011147 kind2 = PyUnicode_KIND(substr);
11148 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011149 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011151 len2 = PyUnicode_GET_LENGTH(substr);
11152 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011153 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011154 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011155 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011156 if (len2 == 1) {
11157 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11158 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011159 return result;
11160 }
11161 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011162 buf2 = _PyUnicode_AsKind(substr, kind1);
11163 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011164 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166
Victor Stinner77282cb2013-04-14 19:22:47 +020011167 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 case PyUnicode_1BYTE_KIND:
11169 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11170 break;
11171 case PyUnicode_2BYTE_KIND:
11172 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11173 break;
11174 case PyUnicode_4BYTE_KIND:
11175 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11176 break;
11177 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011178 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011180
Victor Stinner77282cb2013-04-14 19:22:47 +020011181 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011182 PyMem_Free(buf2);
11183
Guido van Rossum403d68b2000-03-13 15:55:09 +000011184 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011185}
11186
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187/* Concat to string or Unicode object giving a new Unicode object. */
11188
Alexander Belopolsky40018472011-02-26 01:02:56 +000011189PyObject *
11190PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011192 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011193 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011194 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011196 if (ensure_unicode(left) < 0)
11197 return NULL;
11198
11199 if (!PyUnicode_Check(right)) {
11200 PyErr_Format(PyExc_TypeError,
11201 "can only concatenate str (not \"%.200s\") to str",
11202 right->ob_type->tp_name);
11203 return NULL;
11204 }
11205 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011206 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
11208 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011209 if (left == unicode_empty)
11210 return PyUnicode_FromObject(right);
11211 if (right == unicode_empty)
11212 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011214 left_len = PyUnicode_GET_LENGTH(left);
11215 right_len = PyUnicode_GET_LENGTH(right);
11216 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011217 PyErr_SetString(PyExc_OverflowError,
11218 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011219 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011220 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011221 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011222
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011223 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11224 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011225 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011228 result = PyUnicode_New(new_len, maxchar);
11229 if (result == NULL)
11230 return NULL;
11231 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11232 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11233 assert(_PyUnicode_CheckConsistency(result, 1));
11234 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235}
11236
Walter Dörwald1ab83302007-05-18 17:15:44 +000011237void
Victor Stinner23e56682011-10-03 03:54:37 +020011238PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011239{
Victor Stinner23e56682011-10-03 03:54:37 +020011240 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011241 Py_UCS4 maxchar, maxchar2;
11242 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011243
11244 if (p_left == NULL) {
11245 if (!PyErr_Occurred())
11246 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011247 return;
11248 }
Victor Stinner23e56682011-10-03 03:54:37 +020011249 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011250 if (right == NULL || left == NULL
11251 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011252 if (!PyErr_Occurred())
11253 PyErr_BadInternalCall();
11254 goto error;
11255 }
11256
Benjamin Petersonbac79492012-01-14 13:34:47 -050011257 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011258 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011259 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011260 goto error;
11261
Victor Stinner488fa492011-12-12 00:01:39 +010011262 /* Shortcuts */
11263 if (left == unicode_empty) {
11264 Py_DECREF(left);
11265 Py_INCREF(right);
11266 *p_left = right;
11267 return;
11268 }
11269 if (right == unicode_empty)
11270 return;
11271
11272 left_len = PyUnicode_GET_LENGTH(left);
11273 right_len = PyUnicode_GET_LENGTH(right);
11274 if (left_len > PY_SSIZE_T_MAX - right_len) {
11275 PyErr_SetString(PyExc_OverflowError,
11276 "strings are too large to concat");
11277 goto error;
11278 }
11279 new_len = left_len + right_len;
11280
11281 if (unicode_modifiable(left)
11282 && PyUnicode_CheckExact(right)
11283 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011284 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11285 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011286 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011287 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011288 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11289 {
11290 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011291 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011292 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011293
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011294 /* copy 'right' into the newly allocated area of 'left' */
11295 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011296 }
Victor Stinner488fa492011-12-12 00:01:39 +010011297 else {
11298 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11299 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011300 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011301
Victor Stinner488fa492011-12-12 00:01:39 +010011302 /* Concat the two Unicode strings */
11303 res = PyUnicode_New(new_len, maxchar);
11304 if (res == NULL)
11305 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011306 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11307 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011308 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011309 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011310 }
11311 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011312 return;
11313
11314error:
Victor Stinner488fa492011-12-12 00:01:39 +010011315 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011316}
11317
11318void
11319PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11320{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011321 PyUnicode_Append(pleft, right);
11322 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011323}
11324
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011325/*
11326Wraps stringlib_parse_args_finds() and additionally ensures that the
11327first argument is a unicode object.
11328*/
11329
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011330static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011331parse_args_finds_unicode(const char * function_name, PyObject *args,
11332 PyObject **substring,
11333 Py_ssize_t *start, Py_ssize_t *end)
11334{
11335 if(stringlib_parse_args_finds(function_name, args, substring,
11336 start, end)) {
11337 if (ensure_unicode(*substring) < 0)
11338 return 0;
11339 return 1;
11340 }
11341 return 0;
11342}
11343
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011344PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011345 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011346\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011347Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011348string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011349interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350
11351static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011352unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011354 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011355 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011356 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011358 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011359 void *buf1, *buf2;
11360 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011362 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011364
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 kind1 = PyUnicode_KIND(self);
11366 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011367 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011368 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011370 len1 = PyUnicode_GET_LENGTH(self);
11371 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011373 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011374 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011375
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011376 buf1 = PyUnicode_DATA(self);
11377 buf2 = PyUnicode_DATA(substring);
11378 if (kind2 != kind1) {
11379 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011380 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011381 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011382 }
11383 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011384 case PyUnicode_1BYTE_KIND:
11385 iresult = ucs1lib_count(
11386 ((Py_UCS1*)buf1) + start, end - start,
11387 buf2, len2, PY_SSIZE_T_MAX
11388 );
11389 break;
11390 case PyUnicode_2BYTE_KIND:
11391 iresult = ucs2lib_count(
11392 ((Py_UCS2*)buf1) + start, end - start,
11393 buf2, len2, PY_SSIZE_T_MAX
11394 );
11395 break;
11396 case PyUnicode_4BYTE_KIND:
11397 iresult = ucs4lib_count(
11398 ((Py_UCS4*)buf1) + start, end - start,
11399 buf2, len2, PY_SSIZE_T_MAX
11400 );
11401 break;
11402 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011403 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011404 }
11405
11406 result = PyLong_FromSsize_t(iresult);
11407
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011408 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411 return result;
11412}
11413
INADA Naoki3ae20562017-01-16 20:41:20 +090011414/*[clinic input]
11415str.encode as unicode_encode
11416
11417 encoding: str(c_default="NULL") = 'utf-8'
11418 The encoding in which to encode the string.
11419 errors: str(c_default="NULL") = 'strict'
11420 The error handling scheme to use for encoding errors.
11421 The default is 'strict' meaning that encoding errors raise a
11422 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11423 'xmlcharrefreplace' as well as any other name registered with
11424 codecs.register_error that can handle UnicodeEncodeErrors.
11425
11426Encode the string using the codec registered for encoding.
11427[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428
11429static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011430unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011431/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011433 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011434}
11435
INADA Naoki3ae20562017-01-16 20:41:20 +090011436/*[clinic input]
11437str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438
INADA Naoki3ae20562017-01-16 20:41:20 +090011439 tabsize: int = 8
11440
11441Return a copy where all tab characters are expanded using spaces.
11442
11443If tabsize is not given, a tab size of 8 characters is assumed.
11444[clinic start generated code]*/
11445
11446static PyObject *
11447unicode_expandtabs_impl(PyObject *self, int tabsize)
11448/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 Py_ssize_t i, j, line_pos, src_len, incr;
11451 Py_UCS4 ch;
11452 PyObject *u;
11453 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011454 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011455 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456
Antoine Pitrou22425222011-10-04 19:10:51 +020011457 if (PyUnicode_READY(self) == -1)
11458 return NULL;
11459
Thomas Wouters7e474022000-07-16 12:04:32 +000011460 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011461 src_len = PyUnicode_GET_LENGTH(self);
11462 i = j = line_pos = 0;
11463 kind = PyUnicode_KIND(self);
11464 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011465 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011466 for (; i < src_len; i++) {
11467 ch = PyUnicode_READ(kind, src_data, i);
11468 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011469 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011470 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011471 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011472 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011473 goto overflow;
11474 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011476 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011479 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011480 goto overflow;
11481 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011483 if (ch == '\n' || ch == '\r')
11484 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011487 if (!found)
11488 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011489
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011491 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 if (!u)
11493 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011494 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495
Antoine Pitroue71d5742011-10-04 15:55:09 +020011496 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497
Antoine Pitroue71d5742011-10-04 15:55:09 +020011498 for (; i < src_len; i++) {
11499 ch = PyUnicode_READ(kind, src_data, i);
11500 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011502 incr = tabsize - (line_pos % tabsize);
11503 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011504 FILL(kind, dest_data, ' ', j, incr);
11505 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011507 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011508 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011509 line_pos++;
11510 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011511 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011512 if (ch == '\n' || ch == '\r')
11513 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011515 }
11516 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011517 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011518
Antoine Pitroue71d5742011-10-04 15:55:09 +020011519 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011520 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11521 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522}
11523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011524PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011525 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526\n\
11527Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011528such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529arguments start and end are interpreted as in slice notation.\n\
11530\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011531Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532
11533static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011536 /* initialize variables to prevent gcc warning */
11537 PyObject *substring = NULL;
11538 Py_ssize_t start = 0;
11539 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011540 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011542 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011545 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011546 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011548 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 if (result == -2)
11551 return NULL;
11552
Christian Heimes217cfd12007-12-02 14:31:20 +000011553 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554}
11555
11556static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011557unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011559 void *data;
11560 enum PyUnicode_Kind kind;
11561 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011562
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011563 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011564 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011565 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011566 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011567 if (PyUnicode_READY(self) == -1) {
11568 return NULL;
11569 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011570 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11571 PyErr_SetString(PyExc_IndexError, "string index out of range");
11572 return NULL;
11573 }
11574 kind = PyUnicode_KIND(self);
11575 data = PyUnicode_DATA(self);
11576 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011577 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578}
11579
Guido van Rossumc2504932007-09-18 19:42:40 +000011580/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011581 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011582static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011583unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584{
Guido van Rossumc2504932007-09-18 19:42:40 +000011585 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011586 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011587
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011588#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011589 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011590#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 if (_PyUnicode_HASH(self) != -1)
11592 return _PyUnicode_HASH(self);
11593 if (PyUnicode_READY(self) == -1)
11594 return -1;
11595 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011596 /*
11597 We make the hash of the empty string be 0, rather than using
11598 (prefix ^ suffix), since this slightly obfuscates the hash secret
11599 */
11600 if (len == 0) {
11601 _PyUnicode_HASH(self) = 0;
11602 return 0;
11603 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011604 x = _Py_HashBytes(PyUnicode_DATA(self),
11605 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011606 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011607 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608}
11609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011610PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011611 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011613Return the lowest index in S where substring sub is found, \n\
11614such that sub is contained within S[start:end]. Optional\n\
11615arguments start and end are interpreted as in slice notation.\n\
11616\n\
11617Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618
11619static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011622 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011623 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011624 PyObject *substring = NULL;
11625 Py_ssize_t start = 0;
11626 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011628 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011631 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011634 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 if (result == -2)
11637 return NULL;
11638
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639 if (result < 0) {
11640 PyErr_SetString(PyExc_ValueError, "substring not found");
11641 return NULL;
11642 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011643
Christian Heimes217cfd12007-12-02 14:31:20 +000011644 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011645}
11646
INADA Naoki3ae20562017-01-16 20:41:20 +090011647/*[clinic input]
11648str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011649
INADA Naoki3ae20562017-01-16 20:41:20 +090011650Return True if the string is a lowercase string, False otherwise.
11651
11652A string is lowercase if all cased characters in the string are lowercase and
11653there is at least one cased character in the string.
11654[clinic start generated code]*/
11655
11656static PyObject *
11657unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011658/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011660 Py_ssize_t i, length;
11661 int kind;
11662 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663 int cased;
11664
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011665 if (PyUnicode_READY(self) == -1)
11666 return NULL;
11667 length = PyUnicode_GET_LENGTH(self);
11668 kind = PyUnicode_KIND(self);
11669 data = PyUnicode_DATA(self);
11670
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 if (length == 1)
11673 return PyBool_FromLong(
11674 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011676 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011678 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011679
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 for (i = 0; i < length; i++) {
11682 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011683
Benjamin Peterson29060642009-01-31 22:14:21 +000011684 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011685 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011686 else if (!cased && Py_UNICODE_ISLOWER(ch))
11687 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011689 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690}
11691
INADA Naoki3ae20562017-01-16 20:41:20 +090011692/*[clinic input]
11693str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694
INADA Naoki3ae20562017-01-16 20:41:20 +090011695Return True if the string is an uppercase string, False otherwise.
11696
11697A string is uppercase if all cased characters in the string are uppercase and
11698there is at least one cased character in the string.
11699[clinic start generated code]*/
11700
11701static PyObject *
11702unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011703/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 Py_ssize_t i, length;
11706 int kind;
11707 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708 int cased;
11709
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 if (PyUnicode_READY(self) == -1)
11711 return NULL;
11712 length = PyUnicode_GET_LENGTH(self);
11713 kind = PyUnicode_KIND(self);
11714 data = PyUnicode_DATA(self);
11715
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 if (length == 1)
11718 return PyBool_FromLong(
11719 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011721 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011723 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011724
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 for (i = 0; i < length; i++) {
11727 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011728
Benjamin Peterson29060642009-01-31 22:14:21 +000011729 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011730 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011731 else if (!cased && Py_UNICODE_ISUPPER(ch))
11732 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011734 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735}
11736
INADA Naoki3ae20562017-01-16 20:41:20 +090011737/*[clinic input]
11738str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739
INADA Naoki3ae20562017-01-16 20:41:20 +090011740Return True if the string is a title-cased string, False otherwise.
11741
11742In a title-cased string, upper- and title-case characters may only
11743follow uncased characters and lowercase characters only cased ones.
11744[clinic start generated code]*/
11745
11746static PyObject *
11747unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011748/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011750 Py_ssize_t i, length;
11751 int kind;
11752 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753 int cased, previous_is_cased;
11754
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011755 if (PyUnicode_READY(self) == -1)
11756 return NULL;
11757 length = PyUnicode_GET_LENGTH(self);
11758 kind = PyUnicode_KIND(self);
11759 data = PyUnicode_DATA(self);
11760
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 if (length == 1) {
11763 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11764 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11765 (Py_UNICODE_ISUPPER(ch) != 0));
11766 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011767
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011768 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011770 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011771
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772 cased = 0;
11773 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011774 for (i = 0; i < length; i++) {
11775 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011776
Benjamin Peterson29060642009-01-31 22:14:21 +000011777 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11778 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011779 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011780 previous_is_cased = 1;
11781 cased = 1;
11782 }
11783 else if (Py_UNICODE_ISLOWER(ch)) {
11784 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011785 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011786 previous_is_cased = 1;
11787 cased = 1;
11788 }
11789 else
11790 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011792 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793}
11794
INADA Naoki3ae20562017-01-16 20:41:20 +090011795/*[clinic input]
11796str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797
INADA Naoki3ae20562017-01-16 20:41:20 +090011798Return True if the string is a whitespace string, False otherwise.
11799
11800A string is whitespace if all characters in the string are whitespace and there
11801is at least one character in the string.
11802[clinic start generated code]*/
11803
11804static PyObject *
11805unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011806/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 Py_ssize_t i, length;
11809 int kind;
11810 void *data;
11811
11812 if (PyUnicode_READY(self) == -1)
11813 return NULL;
11814 length = PyUnicode_GET_LENGTH(self);
11815 kind = PyUnicode_KIND(self);
11816 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817
Guido van Rossumd57fd912000-03-10 22:53:23 +000011818 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819 if (length == 1)
11820 return PyBool_FromLong(
11821 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011823 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011825 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 for (i = 0; i < length; i++) {
11828 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011829 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011830 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011832 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833}
11834
INADA Naoki3ae20562017-01-16 20:41:20 +090011835/*[clinic input]
11836str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011837
INADA Naoki3ae20562017-01-16 20:41:20 +090011838Return True if the string is an alphabetic string, False otherwise.
11839
11840A string is alphabetic if all characters in the string are alphabetic and there
11841is at least one character in the string.
11842[clinic start generated code]*/
11843
11844static PyObject *
11845unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011846/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011847{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 Py_ssize_t i, length;
11849 int kind;
11850 void *data;
11851
11852 if (PyUnicode_READY(self) == -1)
11853 return NULL;
11854 length = PyUnicode_GET_LENGTH(self);
11855 kind = PyUnicode_KIND(self);
11856 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011857
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011858 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 if (length == 1)
11860 return PyBool_FromLong(
11861 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011862
11863 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011865 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011866
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 for (i = 0; i < length; i++) {
11868 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011869 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011870 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011871 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011872}
11873
INADA Naoki3ae20562017-01-16 20:41:20 +090011874/*[clinic input]
11875str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011876
INADA Naoki3ae20562017-01-16 20:41:20 +090011877Return True if the string is an alpha-numeric string, False otherwise.
11878
11879A string is alpha-numeric if all characters in the string are alpha-numeric and
11880there is at least one character in the string.
11881[clinic start generated code]*/
11882
11883static PyObject *
11884unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011885/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011886{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011887 int kind;
11888 void *data;
11889 Py_ssize_t len, i;
11890
11891 if (PyUnicode_READY(self) == -1)
11892 return NULL;
11893
11894 kind = PyUnicode_KIND(self);
11895 data = PyUnicode_DATA(self);
11896 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011897
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011898 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899 if (len == 1) {
11900 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11901 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11902 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011903
11904 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011905 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011906 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011907
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 for (i = 0; i < len; i++) {
11909 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011910 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011911 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011912 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011913 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011914}
11915
INADA Naoki3ae20562017-01-16 20:41:20 +090011916/*[clinic input]
11917str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918
INADA Naoki3ae20562017-01-16 20:41:20 +090011919Return True if the string is a decimal string, False otherwise.
11920
11921A string is a decimal string if all characters in the string are decimal and
11922there is at least one character in the string.
11923[clinic start generated code]*/
11924
11925static PyObject *
11926unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011927/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011929 Py_ssize_t i, length;
11930 int kind;
11931 void *data;
11932
11933 if (PyUnicode_READY(self) == -1)
11934 return NULL;
11935 length = PyUnicode_GET_LENGTH(self);
11936 kind = PyUnicode_KIND(self);
11937 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011940 if (length == 1)
11941 return PyBool_FromLong(
11942 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011944 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011946 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 for (i = 0; i < length; i++) {
11949 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011950 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011952 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953}
11954
INADA Naoki3ae20562017-01-16 20:41:20 +090011955/*[clinic input]
11956str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957
INADA Naoki3ae20562017-01-16 20:41:20 +090011958Return True if the string is a digit string, False otherwise.
11959
11960A string is a digit string if all characters in the string are digits and there
11961is at least one character in the string.
11962[clinic start generated code]*/
11963
11964static PyObject *
11965unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011966/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011967{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 Py_ssize_t i, length;
11969 int kind;
11970 void *data;
11971
11972 if (PyUnicode_READY(self) == -1)
11973 return NULL;
11974 length = PyUnicode_GET_LENGTH(self);
11975 kind = PyUnicode_KIND(self);
11976 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011977
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 if (length == 1) {
11980 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11981 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11982 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011984 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011986 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011987
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 for (i = 0; i < length; i++) {
11989 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011990 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011991 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011992 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993}
11994
INADA Naoki3ae20562017-01-16 20:41:20 +090011995/*[clinic input]
11996str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997
INADA Naoki3ae20562017-01-16 20:41:20 +090011998Return True if the string is a numeric string, False otherwise.
11999
12000A string is numeric if all characters in the string are numeric and there is at
12001least one character in the string.
12002[clinic start generated code]*/
12003
12004static PyObject *
12005unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012006/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012008 Py_ssize_t i, length;
12009 int kind;
12010 void *data;
12011
12012 if (PyUnicode_READY(self) == -1)
12013 return NULL;
12014 length = PyUnicode_GET_LENGTH(self);
12015 kind = PyUnicode_KIND(self);
12016 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012017
Guido van Rossumd57fd912000-03-10 22:53:23 +000012018 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 if (length == 1)
12020 return PyBool_FromLong(
12021 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012022
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012023 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012025 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012027 for (i = 0; i < length; i++) {
12028 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012029 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012031 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012032}
12033
Martin v. Löwis47383402007-08-15 07:32:56 +000012034int
12035PyUnicode_IsIdentifier(PyObject *self)
12036{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012037 int kind;
12038 void *data;
12039 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012040 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012042 if (PyUnicode_READY(self) == -1) {
12043 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012044 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 }
12046
12047 /* Special case for empty strings */
12048 if (PyUnicode_GET_LENGTH(self) == 0)
12049 return 0;
12050 kind = PyUnicode_KIND(self);
12051 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012052
12053 /* PEP 3131 says that the first character must be in
12054 XID_Start and subsequent characters in XID_Continue,
12055 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012056 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012057 letters, digits, underscore). However, given the current
12058 definition of XID_Start and XID_Continue, it is sufficient
12059 to check just for these, except that _ must be allowed
12060 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012062 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012063 return 0;
12064
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012065 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012066 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012067 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012068 return 1;
12069}
12070
INADA Naoki3ae20562017-01-16 20:41:20 +090012071/*[clinic input]
12072str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012073
INADA Naoki3ae20562017-01-16 20:41:20 +090012074Return True if the string is a valid Python identifier, False otherwise.
12075
12076Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12077"class".
12078[clinic start generated code]*/
12079
12080static PyObject *
12081unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012082/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012083{
12084 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12085}
12086
INADA Naoki3ae20562017-01-16 20:41:20 +090012087/*[clinic input]
12088str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012089
INADA Naoki3ae20562017-01-16 20:41:20 +090012090Return True if the string is printable, False otherwise.
12091
12092A string is printable if all of its characters are considered printable in
12093repr() or if it is empty.
12094[clinic start generated code]*/
12095
12096static PyObject *
12097unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012098/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012099{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012100 Py_ssize_t i, length;
12101 int kind;
12102 void *data;
12103
12104 if (PyUnicode_READY(self) == -1)
12105 return NULL;
12106 length = PyUnicode_GET_LENGTH(self);
12107 kind = PyUnicode_KIND(self);
12108 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012109
12110 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 if (length == 1)
12112 return PyBool_FromLong(
12113 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115 for (i = 0; i < length; i++) {
12116 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012117 Py_RETURN_FALSE;
12118 }
12119 }
12120 Py_RETURN_TRUE;
12121}
12122
INADA Naoki3ae20562017-01-16 20:41:20 +090012123/*[clinic input]
12124str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125
INADA Naoki3ae20562017-01-16 20:41:20 +090012126 iterable: object
12127 /
12128
12129Concatenate any number of strings.
12130
Martin Panter91a88662017-01-24 00:30:06 +000012131The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012132The result is returned as a new string.
12133
12134Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12135[clinic start generated code]*/
12136
12137static PyObject *
12138unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012139/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012140{
INADA Naoki3ae20562017-01-16 20:41:20 +090012141 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142}
12143
Martin v. Löwis18e16552006-02-15 17:27:45 +000012144static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012145unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 if (PyUnicode_READY(self) == -1)
12148 return -1;
12149 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150}
12151
INADA Naoki3ae20562017-01-16 20:41:20 +090012152/*[clinic input]
12153str.ljust as unicode_ljust
12154
12155 width: Py_ssize_t
12156 fillchar: Py_UCS4 = ' '
12157 /
12158
12159Return a left-justified string of length width.
12160
12161Padding is done using the specified fill character (default is a space).
12162[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163
12164static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012165unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12166/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012167{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012168 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012169 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170
Victor Stinnerc4b49542011-12-11 22:44:26 +010012171 if (PyUnicode_GET_LENGTH(self) >= width)
12172 return unicode_result_unchanged(self);
12173
12174 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175}
12176
INADA Naoki3ae20562017-01-16 20:41:20 +090012177/*[clinic input]
12178str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
INADA Naoki3ae20562017-01-16 20:41:20 +090012180Return a copy of the string converted to lowercase.
12181[clinic start generated code]*/
12182
12183static PyObject *
12184unicode_lower_impl(PyObject *self)
12185/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012187 if (PyUnicode_READY(self) == -1)
12188 return NULL;
12189 if (PyUnicode_IS_ASCII(self))
12190 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012191 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192}
12193
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012194#define LEFTSTRIP 0
12195#define RIGHTSTRIP 1
12196#define BOTHSTRIP 2
12197
12198/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012199static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012200
INADA Naoki3ae20562017-01-16 20:41:20 +090012201#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012202
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012203/* externally visible for str.strip(unicode) */
12204PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012205_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012206{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012207 void *data;
12208 int kind;
12209 Py_ssize_t i, j, len;
12210 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012211 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12214 return NULL;
12215
12216 kind = PyUnicode_KIND(self);
12217 data = PyUnicode_DATA(self);
12218 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012219 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12221 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012222 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012223
Benjamin Peterson14339b62009-01-31 16:36:08 +000012224 i = 0;
12225 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012226 while (i < len) {
12227 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12228 if (!BLOOM(sepmask, ch))
12229 break;
12230 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12231 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012232 i++;
12233 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012234 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012235
Benjamin Peterson14339b62009-01-31 16:36:08 +000012236 j = len;
12237 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012238 j--;
12239 while (j >= i) {
12240 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12241 if (!BLOOM(sepmask, ch))
12242 break;
12243 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12244 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012245 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012246 }
12247
Benjamin Peterson29060642009-01-31 22:14:21 +000012248 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012249 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012250
Victor Stinner7931d9a2011-11-04 00:22:48 +010012251 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012252}
12253
12254PyObject*
12255PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12256{
12257 unsigned char *data;
12258 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012259 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012260
Victor Stinnerde636f32011-10-01 03:55:54 +020012261 if (PyUnicode_READY(self) == -1)
12262 return NULL;
12263
Victor Stinner684d5fd2012-05-03 02:32:34 +020012264 length = PyUnicode_GET_LENGTH(self);
12265 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012266
Victor Stinner684d5fd2012-05-03 02:32:34 +020012267 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012268 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012269
Victor Stinnerde636f32011-10-01 03:55:54 +020012270 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012271 PyErr_SetString(PyExc_IndexError, "string index out of range");
12272 return NULL;
12273 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012274 if (start >= length || end < start)
12275 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012276
Victor Stinner684d5fd2012-05-03 02:32:34 +020012277 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012278 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012279 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012280 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012281 }
12282 else {
12283 kind = PyUnicode_KIND(self);
12284 data = PyUnicode_1BYTE_DATA(self);
12285 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012286 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012287 length);
12288 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290
12291static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012292do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 Py_ssize_t len, i, j;
12295
12296 if (PyUnicode_READY(self) == -1)
12297 return NULL;
12298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012299 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012300
Victor Stinnercc7af722013-04-09 22:39:24 +020012301 if (PyUnicode_IS_ASCII(self)) {
12302 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12303
12304 i = 0;
12305 if (striptype != RIGHTSTRIP) {
12306 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012307 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012308 if (!_Py_ascii_whitespace[ch])
12309 break;
12310 i++;
12311 }
12312 }
12313
12314 j = len;
12315 if (striptype != LEFTSTRIP) {
12316 j--;
12317 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012318 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012319 if (!_Py_ascii_whitespace[ch])
12320 break;
12321 j--;
12322 }
12323 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012324 }
12325 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012326 else {
12327 int kind = PyUnicode_KIND(self);
12328 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012329
Victor Stinnercc7af722013-04-09 22:39:24 +020012330 i = 0;
12331 if (striptype != RIGHTSTRIP) {
12332 while (i < len) {
12333 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12334 if (!Py_UNICODE_ISSPACE(ch))
12335 break;
12336 i++;
12337 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012338 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012339
12340 j = len;
12341 if (striptype != LEFTSTRIP) {
12342 j--;
12343 while (j >= i) {
12344 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12345 if (!Py_UNICODE_ISSPACE(ch))
12346 break;
12347 j--;
12348 }
12349 j++;
12350 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012351 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012352
Victor Stinner7931d9a2011-11-04 00:22:48 +010012353 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012354}
12355
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012356
12357static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012358do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012359{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012360 if (sep != NULL && sep != Py_None) {
12361 if (PyUnicode_Check(sep))
12362 return _PyUnicode_XStrip(self, striptype, sep);
12363 else {
12364 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012365 "%s arg must be None or str",
12366 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012367 return NULL;
12368 }
12369 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012370
Benjamin Peterson14339b62009-01-31 16:36:08 +000012371 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012372}
12373
12374
INADA Naoki3ae20562017-01-16 20:41:20 +090012375/*[clinic input]
12376str.strip as unicode_strip
12377
12378 chars: object = None
12379 /
12380
Victor Stinner0c4a8282017-01-17 02:21:47 +010012381Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012382
12383If chars is given and not None, remove characters in chars instead.
12384[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012385
12386static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012387unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012388/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012389{
INADA Naoki3ae20562017-01-16 20:41:20 +090012390 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012391}
12392
12393
INADA Naoki3ae20562017-01-16 20:41:20 +090012394/*[clinic input]
12395str.lstrip as unicode_lstrip
12396
12397 chars: object = NULL
12398 /
12399
12400Return a copy of the string with leading whitespace removed.
12401
12402If chars is given and not None, remove characters in chars instead.
12403[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012404
12405static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012406unicode_lstrip_impl(PyObject *self, PyObject *chars)
12407/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012408{
INADA Naoki3ae20562017-01-16 20:41:20 +090012409 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012410}
12411
12412
INADA Naoki3ae20562017-01-16 20:41:20 +090012413/*[clinic input]
12414str.rstrip as unicode_rstrip
12415
12416 chars: object = NULL
12417 /
12418
12419Return a copy of the string with trailing whitespace removed.
12420
12421If chars is given and not None, remove characters in chars instead.
12422[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012423
12424static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012425unicode_rstrip_impl(PyObject *self, PyObject *chars)
12426/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012427{
INADA Naoki3ae20562017-01-16 20:41:20 +090012428 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012429}
12430
12431
Guido van Rossumd57fd912000-03-10 22:53:23 +000012432static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012433unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012434{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012435 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012436 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437
Serhiy Storchaka05997252013-01-26 12:14:02 +020012438 if (len < 1)
12439 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012440
Victor Stinnerc4b49542011-12-11 22:44:26 +010012441 /* no repeat, return original string */
12442 if (len == 1)
12443 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012444
Benjamin Petersonbac79492012-01-14 13:34:47 -050012445 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012446 return NULL;
12447
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012448 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012449 PyErr_SetString(PyExc_OverflowError,
12450 "repeated string is too long");
12451 return NULL;
12452 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012453 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012454
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012455 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012456 if (!u)
12457 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012458 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012460 if (PyUnicode_GET_LENGTH(str) == 1) {
12461 const int kind = PyUnicode_KIND(str);
12462 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012463 if (kind == PyUnicode_1BYTE_KIND) {
12464 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012465 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012466 }
12467 else if (kind == PyUnicode_2BYTE_KIND) {
12468 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012469 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012470 ucs2[n] = fill_char;
12471 } else {
12472 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12473 assert(kind == PyUnicode_4BYTE_KIND);
12474 for (n = 0; n < len; ++n)
12475 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477 }
12478 else {
12479 /* number of characters copied this far */
12480 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012481 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012483 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012484 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012485 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012487 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012488 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012489 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012490 }
12491
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012492 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012493 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494}
12495
Alexander Belopolsky40018472011-02-26 01:02:56 +000012496PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012497PyUnicode_Replace(PyObject *str,
12498 PyObject *substr,
12499 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012500 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012502 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12503 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012504 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012505 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506}
12507
INADA Naoki3ae20562017-01-16 20:41:20 +090012508/*[clinic input]
12509str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510
INADA Naoki3ae20562017-01-16 20:41:20 +090012511 old: unicode
12512 new: unicode
12513 count: Py_ssize_t = -1
12514 Maximum number of occurrences to replace.
12515 -1 (the default value) means replace all occurrences.
12516 /
12517
12518Return a copy with all occurrences of substring old replaced by new.
12519
12520If the optional argument count is given, only the first count occurrences are
12521replaced.
12522[clinic start generated code]*/
12523
12524static PyObject *
12525unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12526 Py_ssize_t count)
12527/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012529 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012530 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012531 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532}
12533
Alexander Belopolsky40018472011-02-26 01:02:56 +000012534static PyObject *
12535unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012537 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538 Py_ssize_t isize;
12539 Py_ssize_t osize, squote, dquote, i, o;
12540 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012541 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012545 return NULL;
12546
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012547 isize = PyUnicode_GET_LENGTH(unicode);
12548 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550 /* Compute length of output, quote characters, and
12551 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012552 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553 max = 127;
12554 squote = dquote = 0;
12555 ikind = PyUnicode_KIND(unicode);
12556 for (i = 0; i < isize; i++) {
12557 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012558 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012559 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012560 case '\'': squote++; break;
12561 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012563 incr = 2;
12564 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 default:
12566 /* Fast-path ASCII */
12567 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012568 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012569 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012570 ;
12571 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012574 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012576 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012577 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012578 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012580 if (osize > PY_SSIZE_T_MAX - incr) {
12581 PyErr_SetString(PyExc_OverflowError,
12582 "string is too long to generate repr");
12583 return NULL;
12584 }
12585 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012586 }
12587
12588 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012589 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012591 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 if (dquote)
12593 /* Both squote and dquote present. Use squote,
12594 and escape them */
12595 osize += squote;
12596 else
12597 quote = '"';
12598 }
Victor Stinner55c08782013-04-14 18:45:39 +020012599 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012600
12601 repr = PyUnicode_New(osize, max);
12602 if (repr == NULL)
12603 return NULL;
12604 okind = PyUnicode_KIND(repr);
12605 odata = PyUnicode_DATA(repr);
12606
12607 PyUnicode_WRITE(okind, odata, 0, quote);
12608 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012609 if (unchanged) {
12610 _PyUnicode_FastCopyCharacters(repr, 1,
12611 unicode, 0,
12612 isize);
12613 }
12614 else {
12615 for (i = 0, o = 1; i < isize; i++) {
12616 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012617
Victor Stinner55c08782013-04-14 18:45:39 +020012618 /* Escape quotes and backslashes */
12619 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012620 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012621 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012622 continue;
12623 }
12624
12625 /* Map special whitespace to '\t', \n', '\r' */
12626 if (ch == '\t') {
12627 PyUnicode_WRITE(okind, odata, o++, '\\');
12628 PyUnicode_WRITE(okind, odata, o++, 't');
12629 }
12630 else if (ch == '\n') {
12631 PyUnicode_WRITE(okind, odata, o++, '\\');
12632 PyUnicode_WRITE(okind, odata, o++, 'n');
12633 }
12634 else if (ch == '\r') {
12635 PyUnicode_WRITE(okind, odata, o++, '\\');
12636 PyUnicode_WRITE(okind, odata, o++, 'r');
12637 }
12638
12639 /* Map non-printable US ASCII to '\xhh' */
12640 else if (ch < ' ' || ch == 0x7F) {
12641 PyUnicode_WRITE(okind, odata, o++, '\\');
12642 PyUnicode_WRITE(okind, odata, o++, 'x');
12643 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12644 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12645 }
12646
12647 /* Copy ASCII characters as-is */
12648 else if (ch < 0x7F) {
12649 PyUnicode_WRITE(okind, odata, o++, ch);
12650 }
12651
12652 /* Non-ASCII characters */
12653 else {
12654 /* Map Unicode whitespace and control characters
12655 (categories Z* and C* except ASCII space)
12656 */
12657 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12658 PyUnicode_WRITE(okind, odata, o++, '\\');
12659 /* Map 8-bit characters to '\xhh' */
12660 if (ch <= 0xff) {
12661 PyUnicode_WRITE(okind, odata, o++, 'x');
12662 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12663 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12664 }
12665 /* Map 16-bit characters to '\uxxxx' */
12666 else if (ch <= 0xffff) {
12667 PyUnicode_WRITE(okind, odata, o++, 'u');
12668 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12669 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12670 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12671 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12672 }
12673 /* Map 21-bit characters to '\U00xxxxxx' */
12674 else {
12675 PyUnicode_WRITE(okind, odata, o++, 'U');
12676 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12677 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12678 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12679 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12680 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12681 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12682 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12683 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12684 }
12685 }
12686 /* Copy characters as-is */
12687 else {
12688 PyUnicode_WRITE(okind, odata, o++, ch);
12689 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012690 }
12691 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012692 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012693 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012694 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012695 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696}
12697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012698PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012699 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700\n\
12701Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012702such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703arguments start and end are interpreted as in slice notation.\n\
12704\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012705Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706
12707static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012708unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012710 /* initialize variables to prevent gcc warning */
12711 PyObject *substring = NULL;
12712 Py_ssize_t start = 0;
12713 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012714 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012715
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012716 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012717 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012719 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012720 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012722 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 if (result == -2)
12725 return NULL;
12726
Christian Heimes217cfd12007-12-02 14:31:20 +000012727 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728}
12729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012730PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012731 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012733Return the highest index in S where substring sub is found,\n\
12734such that sub is contained within S[start:end]. Optional\n\
12735arguments start and end are interpreted as in slice notation.\n\
12736\n\
12737Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012738
12739static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012742 /* initialize variables to prevent gcc warning */
12743 PyObject *substring = NULL;
12744 Py_ssize_t start = 0;
12745 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012746 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012748 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012749 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012751 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012752 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012753
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012754 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756 if (result == -2)
12757 return NULL;
12758
Guido van Rossumd57fd912000-03-10 22:53:23 +000012759 if (result < 0) {
12760 PyErr_SetString(PyExc_ValueError, "substring not found");
12761 return NULL;
12762 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763
Christian Heimes217cfd12007-12-02 14:31:20 +000012764 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012765}
12766
INADA Naoki3ae20562017-01-16 20:41:20 +090012767/*[clinic input]
12768str.rjust as unicode_rjust
12769
12770 width: Py_ssize_t
12771 fillchar: Py_UCS4 = ' '
12772 /
12773
12774Return a right-justified string of length width.
12775
12776Padding is done using the specified fill character (default is a space).
12777[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778
12779static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012780unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12781/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012783 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784 return NULL;
12785
Victor Stinnerc4b49542011-12-11 22:44:26 +010012786 if (PyUnicode_GET_LENGTH(self) >= width)
12787 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788
Victor Stinnerc4b49542011-12-11 22:44:26 +010012789 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790}
12791
Alexander Belopolsky40018472011-02-26 01:02:56 +000012792PyObject *
12793PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012795 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012796 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012798 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799}
12800
INADA Naoki3ae20562017-01-16 20:41:20 +090012801/*[clinic input]
12802str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803
INADA Naoki3ae20562017-01-16 20:41:20 +090012804 sep: object = None
12805 The delimiter according which to split the string.
12806 None (the default value) means split according to any whitespace,
12807 and discard empty strings from the result.
12808 maxsplit: Py_ssize_t = -1
12809 Maximum number of splits to do.
12810 -1 (the default value) means no limit.
12811
12812Return a list of the words in the string, using sep as the delimiter string.
12813[clinic start generated code]*/
12814
12815static PyObject *
12816unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12817/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818{
INADA Naoki3ae20562017-01-16 20:41:20 +090012819 if (sep == Py_None)
12820 return split(self, NULL, maxsplit);
12821 if (PyUnicode_Check(sep))
12822 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012823
12824 PyErr_Format(PyExc_TypeError,
12825 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012826 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012827 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828}
12829
Thomas Wouters477c8d52006-05-27 19:21:47 +000012830PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012831PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012832{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012833 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012834 int kind1, kind2;
12835 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012837
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012838 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012839 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012840
Victor Stinner14f8f022011-10-05 20:58:25 +020012841 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012842 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012843 len1 = PyUnicode_GET_LENGTH(str_obj);
12844 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012845 if (kind1 < kind2 || len1 < len2) {
12846 _Py_INCREF_UNICODE_EMPTY();
12847 if (!unicode_empty)
12848 out = NULL;
12849 else {
12850 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12851 Py_DECREF(unicode_empty);
12852 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012853 return out;
12854 }
12855 buf1 = PyUnicode_DATA(str_obj);
12856 buf2 = PyUnicode_DATA(sep_obj);
12857 if (kind2 != kind1) {
12858 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12859 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012860 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012861 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012862
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012863 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012864 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012865 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12866 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12867 else
12868 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012869 break;
12870 case PyUnicode_2BYTE_KIND:
12871 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12872 break;
12873 case PyUnicode_4BYTE_KIND:
12874 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12875 break;
12876 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012877 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012879
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012880 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012882
12883 return out;
12884}
12885
12886
12887PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012888PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012889{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012890 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012891 int kind1, kind2;
12892 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012893 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012894
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012895 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012896 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012897
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012898 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012899 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012900 len1 = PyUnicode_GET_LENGTH(str_obj);
12901 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012902 if (kind1 < kind2 || len1 < len2) {
12903 _Py_INCREF_UNICODE_EMPTY();
12904 if (!unicode_empty)
12905 out = NULL;
12906 else {
12907 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12908 Py_DECREF(unicode_empty);
12909 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012910 return out;
12911 }
12912 buf1 = PyUnicode_DATA(str_obj);
12913 buf2 = PyUnicode_DATA(sep_obj);
12914 if (kind2 != kind1) {
12915 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12916 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012917 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012918 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012919
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012920 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012921 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012922 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12923 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12924 else
12925 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012926 break;
12927 case PyUnicode_2BYTE_KIND:
12928 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12929 break;
12930 case PyUnicode_4BYTE_KIND:
12931 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12932 break;
12933 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012934 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012935 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012936
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012937 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012938 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012939
12940 return out;
12941}
12942
INADA Naoki3ae20562017-01-16 20:41:20 +090012943/*[clinic input]
12944str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012945
INADA Naoki3ae20562017-01-16 20:41:20 +090012946 sep: object
12947 /
12948
12949Partition the string into three parts using the given separator.
12950
12951This will search for the separator in the string. If the separator is found,
12952returns a 3-tuple containing the part before the separator, the separator
12953itself, and the part after it.
12954
12955If the separator is not found, returns a 3-tuple containing the original string
12956and two empty strings.
12957[clinic start generated code]*/
12958
12959static PyObject *
12960unicode_partition(PyObject *self, PyObject *sep)
12961/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012962{
INADA Naoki3ae20562017-01-16 20:41:20 +090012963 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012964}
12965
INADA Naoki3ae20562017-01-16 20:41:20 +090012966/*[clinic input]
12967str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012968
INADA Naoki3ae20562017-01-16 20:41:20 +090012969Partition the string into three parts using the given separator.
12970
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012971This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012972the separator is found, returns a 3-tuple containing the part before the
12973separator, the separator itself, and the part after it.
12974
12975If the separator is not found, returns a 3-tuple containing two empty strings
12976and the original string.
12977[clinic start generated code]*/
12978
12979static PyObject *
12980unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012981/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012982{
INADA Naoki3ae20562017-01-16 20:41:20 +090012983 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012984}
12985
Alexander Belopolsky40018472011-02-26 01:02:56 +000012986PyObject *
12987PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012988{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012989 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012990 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012991
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012992 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012993}
12994
INADA Naoki3ae20562017-01-16 20:41:20 +090012995/*[clinic input]
12996str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012997
INADA Naoki3ae20562017-01-16 20:41:20 +090012998Return a list of the words in the string, using sep as the delimiter string.
12999
13000Splits are done starting at the end of the string and working to the front.
13001[clinic start generated code]*/
13002
13003static PyObject *
13004unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13005/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013006{
INADA Naoki3ae20562017-01-16 20:41:20 +090013007 if (sep == Py_None)
13008 return rsplit(self, NULL, maxsplit);
13009 if (PyUnicode_Check(sep))
13010 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013011
13012 PyErr_Format(PyExc_TypeError,
13013 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013014 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013015 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013016}
13017
INADA Naoki3ae20562017-01-16 20:41:20 +090013018/*[clinic input]
13019str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013020
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013021 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013022
13023Return a list of the lines in the string, breaking at line boundaries.
13024
13025Line breaks are not included in the resulting list unless keepends is given and
13026true.
13027[clinic start generated code]*/
13028
13029static PyObject *
13030unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013031/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013032{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013033 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013034}
13035
13036static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013037PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013038{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013039 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040}
13041
INADA Naoki3ae20562017-01-16 20:41:20 +090013042/*[clinic input]
13043str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013044
INADA Naoki3ae20562017-01-16 20:41:20 +090013045Convert uppercase characters to lowercase and lowercase characters to uppercase.
13046[clinic start generated code]*/
13047
13048static PyObject *
13049unicode_swapcase_impl(PyObject *self)
13050/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013051{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013052 if (PyUnicode_READY(self) == -1)
13053 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013054 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013055}
13056
Larry Hastings61272b72014-01-07 12:41:53 -080013057/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013058
Larry Hastings31826802013-10-19 00:09:25 -070013059@staticmethod
13060str.maketrans as unicode_maketrans
13061
13062 x: object
13063
13064 y: unicode=NULL
13065
13066 z: unicode=NULL
13067
13068 /
13069
13070Return a translation table usable for str.translate().
13071
13072If there is only one argument, it must be a dictionary mapping Unicode
13073ordinals (integers) or characters to Unicode ordinals, strings or None.
13074Character keys will be then converted to ordinals.
13075If there are two arguments, they must be strings of equal length, and
13076in the resulting dictionary, each character in x will be mapped to the
13077character at the same position in y. If there is a third argument, it
13078must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013079[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013080
Larry Hastings31826802013-10-19 00:09:25 -070013081static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013082unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013083/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013084{
Georg Brandlceee0772007-11-27 23:48:05 +000013085 PyObject *new = NULL, *key, *value;
13086 Py_ssize_t i = 0;
13087 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013088
Georg Brandlceee0772007-11-27 23:48:05 +000013089 new = PyDict_New();
13090 if (!new)
13091 return NULL;
13092 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013093 int x_kind, y_kind, z_kind;
13094 void *x_data, *y_data, *z_data;
13095
Georg Brandlceee0772007-11-27 23:48:05 +000013096 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013097 if (!PyUnicode_Check(x)) {
13098 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13099 "be a string if there is a second argument");
13100 goto err;
13101 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013102 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013103 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13104 "arguments must have equal length");
13105 goto err;
13106 }
13107 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013108 x_kind = PyUnicode_KIND(x);
13109 y_kind = PyUnicode_KIND(y);
13110 x_data = PyUnicode_DATA(x);
13111 y_data = PyUnicode_DATA(y);
13112 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13113 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013114 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013115 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013116 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013117 if (!value) {
13118 Py_DECREF(key);
13119 goto err;
13120 }
Georg Brandlceee0772007-11-27 23:48:05 +000013121 res = PyDict_SetItem(new, key, value);
13122 Py_DECREF(key);
13123 Py_DECREF(value);
13124 if (res < 0)
13125 goto err;
13126 }
13127 /* create entries for deleting chars in z */
13128 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013129 z_kind = PyUnicode_KIND(z);
13130 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013131 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013132 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013133 if (!key)
13134 goto err;
13135 res = PyDict_SetItem(new, key, Py_None);
13136 Py_DECREF(key);
13137 if (res < 0)
13138 goto err;
13139 }
13140 }
13141 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013142 int kind;
13143 void *data;
13144
Georg Brandlceee0772007-11-27 23:48:05 +000013145 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013146 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013147 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13148 "to maketrans it must be a dict");
13149 goto err;
13150 }
13151 /* copy entries into the new dict, converting string keys to int keys */
13152 while (PyDict_Next(x, &i, &key, &value)) {
13153 if (PyUnicode_Check(key)) {
13154 /* convert string keys to integer keys */
13155 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013156 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013157 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13158 "table must be of length 1");
13159 goto err;
13160 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013161 kind = PyUnicode_KIND(key);
13162 data = PyUnicode_DATA(key);
13163 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013164 if (!newkey)
13165 goto err;
13166 res = PyDict_SetItem(new, newkey, value);
13167 Py_DECREF(newkey);
13168 if (res < 0)
13169 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013170 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013171 /* just keep integer keys */
13172 if (PyDict_SetItem(new, key, value) < 0)
13173 goto err;
13174 } else {
13175 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13176 "be strings or integers");
13177 goto err;
13178 }
13179 }
13180 }
13181 return new;
13182 err:
13183 Py_DECREF(new);
13184 return NULL;
13185}
13186
INADA Naoki3ae20562017-01-16 20:41:20 +090013187/*[clinic input]
13188str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013189
INADA Naoki3ae20562017-01-16 20:41:20 +090013190 table: object
13191 Translation table, which must be a mapping of Unicode ordinals to
13192 Unicode ordinals, strings, or None.
13193 /
13194
13195Replace each character in the string using the given translation table.
13196
13197The table must implement lookup/indexing via __getitem__, for instance a
13198dictionary or list. If this operation raises LookupError, the character is
13199left untouched. Characters mapped to None are deleted.
13200[clinic start generated code]*/
13201
13202static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013203unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013204/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013206 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207}
13208
INADA Naoki3ae20562017-01-16 20:41:20 +090013209/*[clinic input]
13210str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013211
INADA Naoki3ae20562017-01-16 20:41:20 +090013212Return a copy of the string converted to uppercase.
13213[clinic start generated code]*/
13214
13215static PyObject *
13216unicode_upper_impl(PyObject *self)
13217/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013219 if (PyUnicode_READY(self) == -1)
13220 return NULL;
13221 if (PyUnicode_IS_ASCII(self))
13222 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013223 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224}
13225
INADA Naoki3ae20562017-01-16 20:41:20 +090013226/*[clinic input]
13227str.zfill as unicode_zfill
13228
13229 width: Py_ssize_t
13230 /
13231
13232Pad a numeric string with zeros on the left, to fill a field of the given width.
13233
13234The string is never truncated.
13235[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236
13237static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013238unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013239/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013241 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013242 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013243 int kind;
13244 void *data;
13245 Py_UCS4 chr;
13246
Benjamin Petersonbac79492012-01-14 13:34:47 -050013247 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013248 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013249
Victor Stinnerc4b49542011-12-11 22:44:26 +010013250 if (PyUnicode_GET_LENGTH(self) >= width)
13251 return unicode_result_unchanged(self);
13252
13253 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013254
13255 u = pad(self, fill, 0, '0');
13256
Walter Dörwald068325e2002-04-15 13:36:47 +000013257 if (u == NULL)
13258 return NULL;
13259
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013260 kind = PyUnicode_KIND(u);
13261 data = PyUnicode_DATA(u);
13262 chr = PyUnicode_READ(kind, data, fill);
13263
13264 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013265 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013266 PyUnicode_WRITE(kind, data, 0, chr);
13267 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013268 }
13269
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013270 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013271 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013273
13274#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013275static PyObject *
13276unicode__decimal2ascii(PyObject *self)
13277{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013278 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013279}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013280#endif
13281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013282PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013283 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013284\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013285Return True if S starts with the specified prefix, False otherwise.\n\
13286With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013287With optional end, stop comparing S at that position.\n\
13288prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013289
13290static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013291unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013292 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013293{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013294 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013295 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013296 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013297 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013298 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013299
Jesus Ceaac451502011-04-20 17:09:23 +020013300 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013301 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013302 if (PyTuple_Check(subobj)) {
13303 Py_ssize_t i;
13304 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013305 substring = PyTuple_GET_ITEM(subobj, i);
13306 if (!PyUnicode_Check(substring)) {
13307 PyErr_Format(PyExc_TypeError,
13308 "tuple for startswith must only contain str, "
13309 "not %.100s",
13310 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013311 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013312 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013313 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013314 if (result == -1)
13315 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013316 if (result) {
13317 Py_RETURN_TRUE;
13318 }
13319 }
13320 /* nothing matched */
13321 Py_RETURN_FALSE;
13322 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013323 if (!PyUnicode_Check(subobj)) {
13324 PyErr_Format(PyExc_TypeError,
13325 "startswith first arg must be str or "
13326 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013327 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013328 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013329 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013330 if (result == -1)
13331 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013332 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013333}
13334
13335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013336PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013337 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013338\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013339Return True if S ends with the specified suffix, False otherwise.\n\
13340With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013341With optional end, stop comparing S at that position.\n\
13342suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343
13344static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013345unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013346 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013347{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013348 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013349 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013350 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013351 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013352 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353
Jesus Ceaac451502011-04-20 17:09:23 +020013354 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013355 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013356 if (PyTuple_Check(subobj)) {
13357 Py_ssize_t i;
13358 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013359 substring = PyTuple_GET_ITEM(subobj, i);
13360 if (!PyUnicode_Check(substring)) {
13361 PyErr_Format(PyExc_TypeError,
13362 "tuple for endswith must only contain str, "
13363 "not %.100s",
13364 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013365 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013366 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013367 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013368 if (result == -1)
13369 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013370 if (result) {
13371 Py_RETURN_TRUE;
13372 }
13373 }
13374 Py_RETURN_FALSE;
13375 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013376 if (!PyUnicode_Check(subobj)) {
13377 PyErr_Format(PyExc_TypeError,
13378 "endswith first arg must be str or "
13379 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013381 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013382 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013383 if (result == -1)
13384 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013385 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013386}
13387
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013388static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013389_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013390{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013391 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13392 writer->data = PyUnicode_DATA(writer->buffer);
13393
13394 if (!writer->readonly) {
13395 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013396 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013397 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013398 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013399 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13400 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13401 writer->kind = PyUnicode_WCHAR_KIND;
13402 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13403
Victor Stinner8f674cc2013-04-17 23:02:17 +020013404 /* Copy-on-write mode: set buffer size to 0 so
13405 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13406 * next write. */
13407 writer->size = 0;
13408 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013409}
13410
Victor Stinnerd3f08822012-05-29 12:57:52 +020013411void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013412_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013413{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013414 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013415
13416 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013417 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013418
13419 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13420 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13421 writer->kind = PyUnicode_WCHAR_KIND;
13422 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013423}
13424
Victor Stinnerd3f08822012-05-29 12:57:52 +020013425int
13426_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13427 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013428{
13429 Py_ssize_t newlen;
13430 PyObject *newbuffer;
13431
Victor Stinner2740e462016-09-06 16:58:36 -070013432 assert(maxchar <= MAX_UNICODE);
13433
Victor Stinnerca9381e2015-09-22 00:58:32 +020013434 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013435 assert((maxchar > writer->maxchar && length >= 0)
13436 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013437
Victor Stinner202fdca2012-05-07 12:47:02 +020013438 if (length > PY_SSIZE_T_MAX - writer->pos) {
13439 PyErr_NoMemory();
13440 return -1;
13441 }
13442 newlen = writer->pos + length;
13443
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013444 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013445
Victor Stinnerd3f08822012-05-29 12:57:52 +020013446 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013447 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013448 if (writer->overallocate
13449 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13450 /* overallocate to limit the number of realloc() */
13451 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013452 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013453 if (newlen < writer->min_length)
13454 newlen = writer->min_length;
13455
Victor Stinnerd3f08822012-05-29 12:57:52 +020013456 writer->buffer = PyUnicode_New(newlen, maxchar);
13457 if (writer->buffer == NULL)
13458 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013459 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013460 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013461 if (writer->overallocate
13462 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13463 /* overallocate to limit the number of realloc() */
13464 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013465 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013466 if (newlen < writer->min_length)
13467 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013468
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013469 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013470 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013471 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013472 newbuffer = PyUnicode_New(newlen, maxchar);
13473 if (newbuffer == NULL)
13474 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013475 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13476 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013477 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013478 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013479 }
13480 else {
13481 newbuffer = resize_compact(writer->buffer, newlen);
13482 if (newbuffer == NULL)
13483 return -1;
13484 }
13485 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013486 }
13487 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013488 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013489 newbuffer = PyUnicode_New(writer->size, maxchar);
13490 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013491 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013492 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13493 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013494 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013495 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013496 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013497 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013498
13499#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013500}
13501
Victor Stinnerca9381e2015-09-22 00:58:32 +020013502int
13503_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13504 enum PyUnicode_Kind kind)
13505{
13506 Py_UCS4 maxchar;
13507
13508 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13509 assert(writer->kind < kind);
13510
13511 switch (kind)
13512 {
13513 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13514 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13515 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13516 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013517 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013518 }
13519
13520 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13521}
13522
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013523static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013524_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013525{
Victor Stinner2740e462016-09-06 16:58:36 -070013526 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013527 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13528 return -1;
13529 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13530 writer->pos++;
13531 return 0;
13532}
13533
13534int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013535_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13536{
13537 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13538}
13539
13540int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013541_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13542{
13543 Py_UCS4 maxchar;
13544 Py_ssize_t len;
13545
13546 if (PyUnicode_READY(str) == -1)
13547 return -1;
13548 len = PyUnicode_GET_LENGTH(str);
13549 if (len == 0)
13550 return 0;
13551 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13552 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013553 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013554 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013555 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013556 Py_INCREF(str);
13557 writer->buffer = str;
13558 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013559 writer->pos += len;
13560 return 0;
13561 }
13562 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13563 return -1;
13564 }
13565 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13566 str, 0, len);
13567 writer->pos += len;
13568 return 0;
13569}
13570
Victor Stinnere215d962012-10-06 23:03:36 +020013571int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013572_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13573 Py_ssize_t start, Py_ssize_t end)
13574{
13575 Py_UCS4 maxchar;
13576 Py_ssize_t len;
13577
13578 if (PyUnicode_READY(str) == -1)
13579 return -1;
13580
13581 assert(0 <= start);
13582 assert(end <= PyUnicode_GET_LENGTH(str));
13583 assert(start <= end);
13584
13585 if (end == 0)
13586 return 0;
13587
13588 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13589 return _PyUnicodeWriter_WriteStr(writer, str);
13590
13591 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13592 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13593 else
13594 maxchar = writer->maxchar;
13595 len = end - start;
13596
13597 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13598 return -1;
13599
13600 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13601 str, start, len);
13602 writer->pos += len;
13603 return 0;
13604}
13605
13606int
Victor Stinner4a587072013-11-19 12:54:53 +010013607_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13608 const char *ascii, Py_ssize_t len)
13609{
13610 if (len == -1)
13611 len = strlen(ascii);
13612
13613 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13614
13615 if (writer->buffer == NULL && !writer->overallocate) {
13616 PyObject *str;
13617
13618 str = _PyUnicode_FromASCII(ascii, len);
13619 if (str == NULL)
13620 return -1;
13621
13622 writer->readonly = 1;
13623 writer->buffer = str;
13624 _PyUnicodeWriter_Update(writer);
13625 writer->pos += len;
13626 return 0;
13627 }
13628
13629 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13630 return -1;
13631
13632 switch (writer->kind)
13633 {
13634 case PyUnicode_1BYTE_KIND:
13635 {
13636 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13637 Py_UCS1 *data = writer->data;
13638
Christian Heimesf051e432016-09-13 20:22:02 +020013639 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013640 break;
13641 }
13642 case PyUnicode_2BYTE_KIND:
13643 {
13644 _PyUnicode_CONVERT_BYTES(
13645 Py_UCS1, Py_UCS2,
13646 ascii, ascii + len,
13647 (Py_UCS2 *)writer->data + writer->pos);
13648 break;
13649 }
13650 case PyUnicode_4BYTE_KIND:
13651 {
13652 _PyUnicode_CONVERT_BYTES(
13653 Py_UCS1, Py_UCS4,
13654 ascii, ascii + len,
13655 (Py_UCS4 *)writer->data + writer->pos);
13656 break;
13657 }
13658 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013659 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013660 }
13661
13662 writer->pos += len;
13663 return 0;
13664}
13665
13666int
13667_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13668 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013669{
13670 Py_UCS4 maxchar;
13671
13672 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13673 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13674 return -1;
13675 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13676 writer->pos += len;
13677 return 0;
13678}
13679
Victor Stinnerd3f08822012-05-29 12:57:52 +020013680PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013681_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013682{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013683 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013684
Victor Stinnerd3f08822012-05-29 12:57:52 +020013685 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013686 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013687 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013688 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013689
13690 str = writer->buffer;
13691 writer->buffer = NULL;
13692
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013693 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013694 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13695 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013696 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013697
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013698 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13699 PyObject *str2;
13700 str2 = resize_compact(str, writer->pos);
13701 if (str2 == NULL) {
13702 Py_DECREF(str);
13703 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013704 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013705 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013706 }
13707
Victor Stinner15a0bd32013-07-08 22:29:55 +020013708 assert(_PyUnicode_CheckConsistency(str, 1));
13709 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013710}
13711
Victor Stinnerd3f08822012-05-29 12:57:52 +020013712void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013713_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013714{
13715 Py_CLEAR(writer->buffer);
13716}
13717
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013718#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013719
13720PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013721 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013722\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013723Return a formatted version of S, using substitutions from args and kwargs.\n\
13724The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013725
Eric Smith27bbca62010-11-04 17:06:58 +000013726PyDoc_STRVAR(format_map__doc__,
13727 "S.format_map(mapping) -> str\n\
13728\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013729Return a formatted version of S, using substitutions from mapping.\n\
13730The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013731
INADA Naoki3ae20562017-01-16 20:41:20 +090013732/*[clinic input]
13733str.__format__ as unicode___format__
13734
13735 format_spec: unicode
13736 /
13737
13738Return a formatted version of the string as described by format_spec.
13739[clinic start generated code]*/
13740
Eric Smith4a7d76d2008-05-30 18:10:19 +000013741static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013742unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013743/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013744{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013745 _PyUnicodeWriter writer;
13746 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013747
Victor Stinnerd3f08822012-05-29 12:57:52 +020013748 if (PyUnicode_READY(self) == -1)
13749 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013750 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013751 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13752 self, format_spec, 0,
13753 PyUnicode_GET_LENGTH(format_spec));
13754 if (ret == -1) {
13755 _PyUnicodeWriter_Dealloc(&writer);
13756 return NULL;
13757 }
13758 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013759}
13760
INADA Naoki3ae20562017-01-16 20:41:20 +090013761/*[clinic input]
13762str.__sizeof__ as unicode_sizeof
13763
13764Return the size of the string in memory, in bytes.
13765[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013766
13767static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013768unicode_sizeof_impl(PyObject *self)
13769/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013770{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013771 Py_ssize_t size;
13772
13773 /* If it's a compact object, account for base structure +
13774 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013775 if (PyUnicode_IS_COMPACT_ASCII(self))
13776 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13777 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013778 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013779 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013780 else {
13781 /* If it is a two-block object, account for base object, and
13782 for character block if present. */
13783 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013784 if (_PyUnicode_DATA_ANY(self))
13785 size += (PyUnicode_GET_LENGTH(self) + 1) *
13786 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013787 }
13788 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013789 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013790 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13791 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13792 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13793 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013794
13795 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013796}
13797
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013798static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013799unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013800{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013801 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013802 if (!copy)
13803 return NULL;
13804 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013805}
13806
Guido van Rossumd57fd912000-03-10 22:53:23 +000013807static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013808 UNICODE_ENCODE_METHODDEF
13809 UNICODE_REPLACE_METHODDEF
13810 UNICODE_SPLIT_METHODDEF
13811 UNICODE_RSPLIT_METHODDEF
13812 UNICODE_JOIN_METHODDEF
13813 UNICODE_CAPITALIZE_METHODDEF
13814 UNICODE_CASEFOLD_METHODDEF
13815 UNICODE_TITLE_METHODDEF
13816 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013817 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013818 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013819 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013820 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013821 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013822 UNICODE_LJUST_METHODDEF
13823 UNICODE_LOWER_METHODDEF
13824 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013825 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13826 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013827 UNICODE_RJUST_METHODDEF
13828 UNICODE_RSTRIP_METHODDEF
13829 UNICODE_RPARTITION_METHODDEF
13830 UNICODE_SPLITLINES_METHODDEF
13831 UNICODE_STRIP_METHODDEF
13832 UNICODE_SWAPCASE_METHODDEF
13833 UNICODE_TRANSLATE_METHODDEF
13834 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013835 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13836 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013837 UNICODE_ISLOWER_METHODDEF
13838 UNICODE_ISUPPER_METHODDEF
13839 UNICODE_ISTITLE_METHODDEF
13840 UNICODE_ISSPACE_METHODDEF
13841 UNICODE_ISDECIMAL_METHODDEF
13842 UNICODE_ISDIGIT_METHODDEF
13843 UNICODE_ISNUMERIC_METHODDEF
13844 UNICODE_ISALPHA_METHODDEF
13845 UNICODE_ISALNUM_METHODDEF
13846 UNICODE_ISIDENTIFIER_METHODDEF
13847 UNICODE_ISPRINTABLE_METHODDEF
13848 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013849 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013850 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013851 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013852 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013853 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013854#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013855 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013856 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013857#endif
13858
Benjamin Peterson14339b62009-01-31 16:36:08 +000013859 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013860 {NULL, NULL}
13861};
13862
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013863static PyObject *
13864unicode_mod(PyObject *v, PyObject *w)
13865{
Brian Curtindfc80e32011-08-10 20:28:54 -050013866 if (!PyUnicode_Check(v))
13867 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013868 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013869}
13870
13871static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013872 0, /*nb_add*/
13873 0, /*nb_subtract*/
13874 0, /*nb_multiply*/
13875 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013876};
13877
Guido van Rossumd57fd912000-03-10 22:53:23 +000013878static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013879 (lenfunc) unicode_length, /* sq_length */
13880 PyUnicode_Concat, /* sq_concat */
13881 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13882 (ssizeargfunc) unicode_getitem, /* sq_item */
13883 0, /* sq_slice */
13884 0, /* sq_ass_item */
13885 0, /* sq_ass_slice */
13886 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013887};
13888
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013889static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013890unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013891{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013892 if (PyUnicode_READY(self) == -1)
13893 return NULL;
13894
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013895 if (PyIndex_Check(item)) {
13896 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013897 if (i == -1 && PyErr_Occurred())
13898 return NULL;
13899 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013900 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013901 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013902 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013903 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013904 PyObject *result;
13905 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013906 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013907 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013908
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013909 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013910 return NULL;
13911 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013912 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13913 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013914
13915 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013916 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013917 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013918 slicelength == PyUnicode_GET_LENGTH(self)) {
13919 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013920 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013921 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013922 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013923 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013924 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013925 src_kind = PyUnicode_KIND(self);
13926 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013927 if (!PyUnicode_IS_ASCII(self)) {
13928 kind_limit = kind_maxchar_limit(src_kind);
13929 max_char = 0;
13930 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13931 ch = PyUnicode_READ(src_kind, src_data, cur);
13932 if (ch > max_char) {
13933 max_char = ch;
13934 if (max_char >= kind_limit)
13935 break;
13936 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013937 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013938 }
Victor Stinner55c99112011-10-13 01:17:06 +020013939 else
13940 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013941 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013942 if (result == NULL)
13943 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013944 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013945 dest_data = PyUnicode_DATA(result);
13946
13947 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013948 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13949 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013950 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013951 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013952 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013953 } else {
13954 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13955 return NULL;
13956 }
13957}
13958
13959static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013960 (lenfunc)unicode_length, /* mp_length */
13961 (binaryfunc)unicode_subscript, /* mp_subscript */
13962 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013963};
13964
Guido van Rossumd57fd912000-03-10 22:53:23 +000013965
Guido van Rossumd57fd912000-03-10 22:53:23 +000013966/* Helpers for PyUnicode_Format() */
13967
Victor Stinnera47082312012-10-04 02:19:54 +020013968struct unicode_formatter_t {
13969 PyObject *args;
13970 int args_owned;
13971 Py_ssize_t arglen, argidx;
13972 PyObject *dict;
13973
13974 enum PyUnicode_Kind fmtkind;
13975 Py_ssize_t fmtcnt, fmtpos;
13976 void *fmtdata;
13977 PyObject *fmtstr;
13978
13979 _PyUnicodeWriter writer;
13980};
13981
13982struct unicode_format_arg_t {
13983 Py_UCS4 ch;
13984 int flags;
13985 Py_ssize_t width;
13986 int prec;
13987 int sign;
13988};
13989
Guido van Rossumd57fd912000-03-10 22:53:23 +000013990static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013991unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013992{
Victor Stinnera47082312012-10-04 02:19:54 +020013993 Py_ssize_t argidx = ctx->argidx;
13994
13995 if (argidx < ctx->arglen) {
13996 ctx->argidx++;
13997 if (ctx->arglen < 0)
13998 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013999 else
Victor Stinnera47082312012-10-04 02:19:54 +020014000 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014001 }
14002 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014003 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014004 return NULL;
14005}
14006
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014007/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014008
Victor Stinnera47082312012-10-04 02:19:54 +020014009/* Format a float into the writer if the writer is not NULL, or into *p_output
14010 otherwise.
14011
14012 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014013static int
Victor Stinnera47082312012-10-04 02:19:54 +020014014formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14015 PyObject **p_output,
14016 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014017{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014018 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014019 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014020 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014021 int prec;
14022 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014023
Guido van Rossumd57fd912000-03-10 22:53:23 +000014024 x = PyFloat_AsDouble(v);
14025 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014026 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014027
Victor Stinnera47082312012-10-04 02:19:54 +020014028 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014029 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014030 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014031
Victor Stinnera47082312012-10-04 02:19:54 +020014032 if (arg->flags & F_ALT)
14033 dtoa_flags = Py_DTSF_ALT;
14034 else
14035 dtoa_flags = 0;
14036 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014037 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014038 return -1;
14039 len = strlen(p);
14040 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014041 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014042 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014043 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014044 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014045 }
14046 else
14047 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014048 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014049 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014050}
14051
Victor Stinnerd0880d52012-04-27 23:40:13 +020014052/* formatlong() emulates the format codes d, u, o, x and X, and
14053 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14054 * Python's regular ints.
14055 * Return value: a new PyUnicodeObject*, or NULL if error.
14056 * The output string is of the form
14057 * "-"? ("0x" | "0X")? digit+
14058 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14059 * set in flags. The case of hex digits will be correct,
14060 * There will be at least prec digits, zero-filled on the left if
14061 * necessary to get that many.
14062 * val object to be converted
14063 * flags bitmask of format flags; only F_ALT is looked at
14064 * prec minimum number of digits; 0-fill on left if needed
14065 * type a character in [duoxX]; u acts the same as d
14066 *
14067 * CAUTION: o, x and X conversions on regular ints can never
14068 * produce a '-' sign, but can for Python's unbounded ints.
14069 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014070PyObject *
14071_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014072{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014073 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014074 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014075 Py_ssize_t i;
14076 int sign; /* 1 if '-', else 0 */
14077 int len; /* number of characters */
14078 Py_ssize_t llen;
14079 int numdigits; /* len == numnondigits + numdigits */
14080 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014081
Victor Stinnerd0880d52012-04-27 23:40:13 +020014082 /* Avoid exceeding SSIZE_T_MAX */
14083 if (prec > INT_MAX-3) {
14084 PyErr_SetString(PyExc_OverflowError,
14085 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014087 }
14088
14089 assert(PyLong_Check(val));
14090
14091 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014092 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014093 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014094 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014095 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014096 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014097 /* int and int subclasses should print numerically when a numeric */
14098 /* format code is used (see issue18780) */
14099 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014100 break;
14101 case 'o':
14102 numnondigits = 2;
14103 result = PyNumber_ToBase(val, 8);
14104 break;
14105 case 'x':
14106 case 'X':
14107 numnondigits = 2;
14108 result = PyNumber_ToBase(val, 16);
14109 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014110 }
14111 if (!result)
14112 return NULL;
14113
14114 assert(unicode_modifiable(result));
14115 assert(PyUnicode_IS_READY(result));
14116 assert(PyUnicode_IS_ASCII(result));
14117
14118 /* To modify the string in-place, there can only be one reference. */
14119 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014120 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014121 PyErr_BadInternalCall();
14122 return NULL;
14123 }
14124 buf = PyUnicode_DATA(result);
14125 llen = PyUnicode_GET_LENGTH(result);
14126 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014127 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014128 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014129 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014130 return NULL;
14131 }
14132 len = (int)llen;
14133 sign = buf[0] == '-';
14134 numnondigits += sign;
14135 numdigits = len - numnondigits;
14136 assert(numdigits > 0);
14137
14138 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014139 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014140 (type == 'o' || type == 'x' || type == 'X'))) {
14141 assert(buf[sign] == '0');
14142 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14143 buf[sign+1] == 'o');
14144 numnondigits -= 2;
14145 buf += 2;
14146 len -= 2;
14147 if (sign)
14148 buf[0] = '-';
14149 assert(len == numnondigits + numdigits);
14150 assert(numdigits > 0);
14151 }
14152
14153 /* Fill with leading zeroes to meet minimum width. */
14154 if (prec > numdigits) {
14155 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14156 numnondigits + prec);
14157 char *b1;
14158 if (!r1) {
14159 Py_DECREF(result);
14160 return NULL;
14161 }
14162 b1 = PyBytes_AS_STRING(r1);
14163 for (i = 0; i < numnondigits; ++i)
14164 *b1++ = *buf++;
14165 for (i = 0; i < prec - numdigits; i++)
14166 *b1++ = '0';
14167 for (i = 0; i < numdigits; i++)
14168 *b1++ = *buf++;
14169 *b1 = '\0';
14170 Py_DECREF(result);
14171 result = r1;
14172 buf = PyBytes_AS_STRING(result);
14173 len = numnondigits + prec;
14174 }
14175
14176 /* Fix up case for hex conversions. */
14177 if (type == 'X') {
14178 /* Need to convert all lower case letters to upper case.
14179 and need to convert 0x to 0X (and -0x to -0X). */
14180 for (i = 0; i < len; i++)
14181 if (buf[i] >= 'a' && buf[i] <= 'x')
14182 buf[i] -= 'a'-'A';
14183 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014184 if (!PyUnicode_Check(result)
14185 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014186 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014187 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014188 Py_DECREF(result);
14189 result = unicode;
14190 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014191 else if (len != PyUnicode_GET_LENGTH(result)) {
14192 if (PyUnicode_Resize(&result, len) < 0)
14193 Py_CLEAR(result);
14194 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014195 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014196}
14197
Ethan Furmandf3ed242014-01-05 06:50:30 -080014198/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014199 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014200 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014201 * -1 and raise an exception on error */
14202static int
Victor Stinnera47082312012-10-04 02:19:54 +020014203mainformatlong(PyObject *v,
14204 struct unicode_format_arg_t *arg,
14205 PyObject **p_output,
14206 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014207{
14208 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014209 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014210
14211 if (!PyNumber_Check(v))
14212 goto wrongtype;
14213
Ethan Furman9ab74802014-03-21 06:38:46 -070014214 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014215 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014216 if (type == 'o' || type == 'x' || type == 'X') {
14217 iobj = PyNumber_Index(v);
14218 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014219 if (PyErr_ExceptionMatches(PyExc_TypeError))
14220 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014221 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014222 }
14223 }
14224 else {
14225 iobj = PyNumber_Long(v);
14226 if (iobj == NULL ) {
14227 if (PyErr_ExceptionMatches(PyExc_TypeError))
14228 goto wrongtype;
14229 return -1;
14230 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014231 }
14232 assert(PyLong_Check(iobj));
14233 }
14234 else {
14235 iobj = v;
14236 Py_INCREF(iobj);
14237 }
14238
14239 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014240 && arg->width == -1 && arg->prec == -1
14241 && !(arg->flags & (F_SIGN | F_BLANK))
14242 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014243 {
14244 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014245 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014246 int base;
14247
Victor Stinnera47082312012-10-04 02:19:54 +020014248 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014249 {
14250 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014251 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014252 case 'd':
14253 case 'i':
14254 case 'u':
14255 base = 10;
14256 break;
14257 case 'o':
14258 base = 8;
14259 break;
14260 case 'x':
14261 case 'X':
14262 base = 16;
14263 break;
14264 }
14265
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014266 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14267 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014268 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014269 }
14270 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014271 return 1;
14272 }
14273
Ethan Furmanb95b5612015-01-23 20:05:18 -080014274 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014275 Py_DECREF(iobj);
14276 if (res == NULL)
14277 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014278 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014279 return 0;
14280
14281wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014282 switch(type)
14283 {
14284 case 'o':
14285 case 'x':
14286 case 'X':
14287 PyErr_Format(PyExc_TypeError,
14288 "%%%c format: an integer is required, "
14289 "not %.200s",
14290 type, Py_TYPE(v)->tp_name);
14291 break;
14292 default:
14293 PyErr_Format(PyExc_TypeError,
14294 "%%%c format: a number is required, "
14295 "not %.200s",
14296 type, Py_TYPE(v)->tp_name);
14297 break;
14298 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014299 return -1;
14300}
14301
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014302static Py_UCS4
14303formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014304{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014305 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014306 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014307 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014308 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014309 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014310 goto onError;
14311 }
14312 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014313 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014314 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014315 /* make sure number is a type of integer */
14316 if (!PyLong_Check(v)) {
14317 iobj = PyNumber_Index(v);
14318 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014319 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014320 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014321 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014322 Py_DECREF(iobj);
14323 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014324 else {
14325 x = PyLong_AsLong(v);
14326 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014327 if (x == -1 && PyErr_Occurred())
14328 goto onError;
14329
Victor Stinner8faf8212011-12-08 22:14:11 +010014330 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014331 PyErr_SetString(PyExc_OverflowError,
14332 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014333 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014334 }
14335
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014336 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014337 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014338
Benjamin Peterson29060642009-01-31 22:14:21 +000014339 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014340 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014341 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014342 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014343}
14344
Victor Stinnera47082312012-10-04 02:19:54 +020014345/* Parse options of an argument: flags, width, precision.
14346 Handle also "%(name)" syntax.
14347
14348 Return 0 if the argument has been formatted into arg->str.
14349 Return 1 if the argument has been written into ctx->writer,
14350 Raise an exception and return -1 on error. */
14351static int
14352unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14353 struct unicode_format_arg_t *arg)
14354{
14355#define FORMAT_READ(ctx) \
14356 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14357
14358 PyObject *v;
14359
Victor Stinnera47082312012-10-04 02:19:54 +020014360 if (arg->ch == '(') {
14361 /* Get argument value from a dictionary. Example: "%(name)s". */
14362 Py_ssize_t keystart;
14363 Py_ssize_t keylen;
14364 PyObject *key;
14365 int pcount = 1;
14366
14367 if (ctx->dict == NULL) {
14368 PyErr_SetString(PyExc_TypeError,
14369 "format requires a mapping");
14370 return -1;
14371 }
14372 ++ctx->fmtpos;
14373 --ctx->fmtcnt;
14374 keystart = ctx->fmtpos;
14375 /* Skip over balanced parentheses */
14376 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14377 arg->ch = FORMAT_READ(ctx);
14378 if (arg->ch == ')')
14379 --pcount;
14380 else if (arg->ch == '(')
14381 ++pcount;
14382 ctx->fmtpos++;
14383 }
14384 keylen = ctx->fmtpos - keystart - 1;
14385 if (ctx->fmtcnt < 0 || pcount > 0) {
14386 PyErr_SetString(PyExc_ValueError,
14387 "incomplete format key");
14388 return -1;
14389 }
14390 key = PyUnicode_Substring(ctx->fmtstr,
14391 keystart, keystart + keylen);
14392 if (key == NULL)
14393 return -1;
14394 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014395 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014396 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014397 }
14398 ctx->args = PyObject_GetItem(ctx->dict, key);
14399 Py_DECREF(key);
14400 if (ctx->args == NULL)
14401 return -1;
14402 ctx->args_owned = 1;
14403 ctx->arglen = -1;
14404 ctx->argidx = -2;
14405 }
14406
14407 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014408 while (--ctx->fmtcnt >= 0) {
14409 arg->ch = FORMAT_READ(ctx);
14410 ctx->fmtpos++;
14411 switch (arg->ch) {
14412 case '-': arg->flags |= F_LJUST; continue;
14413 case '+': arg->flags |= F_SIGN; continue;
14414 case ' ': arg->flags |= F_BLANK; continue;
14415 case '#': arg->flags |= F_ALT; continue;
14416 case '0': arg->flags |= F_ZERO; continue;
14417 }
14418 break;
14419 }
14420
14421 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014422 if (arg->ch == '*') {
14423 v = unicode_format_getnextarg(ctx);
14424 if (v == NULL)
14425 return -1;
14426 if (!PyLong_Check(v)) {
14427 PyErr_SetString(PyExc_TypeError,
14428 "* wants int");
14429 return -1;
14430 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014431 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014432 if (arg->width == -1 && PyErr_Occurred())
14433 return -1;
14434 if (arg->width < 0) {
14435 arg->flags |= F_LJUST;
14436 arg->width = -arg->width;
14437 }
14438 if (--ctx->fmtcnt >= 0) {
14439 arg->ch = FORMAT_READ(ctx);
14440 ctx->fmtpos++;
14441 }
14442 }
14443 else if (arg->ch >= '0' && arg->ch <= '9') {
14444 arg->width = arg->ch - '0';
14445 while (--ctx->fmtcnt >= 0) {
14446 arg->ch = FORMAT_READ(ctx);
14447 ctx->fmtpos++;
14448 if (arg->ch < '0' || arg->ch > '9')
14449 break;
14450 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14451 mixing signed and unsigned comparison. Since arg->ch is between
14452 '0' and '9', casting to int is safe. */
14453 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14454 PyErr_SetString(PyExc_ValueError,
14455 "width too big");
14456 return -1;
14457 }
14458 arg->width = arg->width*10 + (arg->ch - '0');
14459 }
14460 }
14461
14462 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014463 if (arg->ch == '.') {
14464 arg->prec = 0;
14465 if (--ctx->fmtcnt >= 0) {
14466 arg->ch = FORMAT_READ(ctx);
14467 ctx->fmtpos++;
14468 }
14469 if (arg->ch == '*') {
14470 v = unicode_format_getnextarg(ctx);
14471 if (v == NULL)
14472 return -1;
14473 if (!PyLong_Check(v)) {
14474 PyErr_SetString(PyExc_TypeError,
14475 "* wants int");
14476 return -1;
14477 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014478 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014479 if (arg->prec == -1 && PyErr_Occurred())
14480 return -1;
14481 if (arg->prec < 0)
14482 arg->prec = 0;
14483 if (--ctx->fmtcnt >= 0) {
14484 arg->ch = FORMAT_READ(ctx);
14485 ctx->fmtpos++;
14486 }
14487 }
14488 else if (arg->ch >= '0' && arg->ch <= '9') {
14489 arg->prec = arg->ch - '0';
14490 while (--ctx->fmtcnt >= 0) {
14491 arg->ch = FORMAT_READ(ctx);
14492 ctx->fmtpos++;
14493 if (arg->ch < '0' || arg->ch > '9')
14494 break;
14495 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14496 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014497 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014498 return -1;
14499 }
14500 arg->prec = arg->prec*10 + (arg->ch - '0');
14501 }
14502 }
14503 }
14504
14505 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14506 if (ctx->fmtcnt >= 0) {
14507 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14508 if (--ctx->fmtcnt >= 0) {
14509 arg->ch = FORMAT_READ(ctx);
14510 ctx->fmtpos++;
14511 }
14512 }
14513 }
14514 if (ctx->fmtcnt < 0) {
14515 PyErr_SetString(PyExc_ValueError,
14516 "incomplete format");
14517 return -1;
14518 }
14519 return 0;
14520
14521#undef FORMAT_READ
14522}
14523
14524/* Format one argument. Supported conversion specifiers:
14525
14526 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014527 - "i", "d", "u": int or float
14528 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014529 - "e", "E", "f", "F", "g", "G": float
14530 - "c": int or str (1 character)
14531
Victor Stinner8dbd4212012-12-04 09:30:24 +010014532 When possible, the output is written directly into the Unicode writer
14533 (ctx->writer). A string is created when padding is required.
14534
Victor Stinnera47082312012-10-04 02:19:54 +020014535 Return 0 if the argument has been formatted into *p_str,
14536 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014537 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014538static int
14539unicode_format_arg_format(struct unicode_formatter_t *ctx,
14540 struct unicode_format_arg_t *arg,
14541 PyObject **p_str)
14542{
14543 PyObject *v;
14544 _PyUnicodeWriter *writer = &ctx->writer;
14545
14546 if (ctx->fmtcnt == 0)
14547 ctx->writer.overallocate = 0;
14548
Victor Stinnera47082312012-10-04 02:19:54 +020014549 v = unicode_format_getnextarg(ctx);
14550 if (v == NULL)
14551 return -1;
14552
Victor Stinnera47082312012-10-04 02:19:54 +020014553
14554 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014555 case 's':
14556 case 'r':
14557 case 'a':
14558 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14559 /* Fast path */
14560 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14561 return -1;
14562 return 1;
14563 }
14564
14565 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14566 *p_str = v;
14567 Py_INCREF(*p_str);
14568 }
14569 else {
14570 if (arg->ch == 's')
14571 *p_str = PyObject_Str(v);
14572 else if (arg->ch == 'r')
14573 *p_str = PyObject_Repr(v);
14574 else
14575 *p_str = PyObject_ASCII(v);
14576 }
14577 break;
14578
14579 case 'i':
14580 case 'd':
14581 case 'u':
14582 case 'o':
14583 case 'x':
14584 case 'X':
14585 {
14586 int ret = mainformatlong(v, arg, p_str, writer);
14587 if (ret != 0)
14588 return ret;
14589 arg->sign = 1;
14590 break;
14591 }
14592
14593 case 'e':
14594 case 'E':
14595 case 'f':
14596 case 'F':
14597 case 'g':
14598 case 'G':
14599 if (arg->width == -1 && arg->prec == -1
14600 && !(arg->flags & (F_SIGN | F_BLANK)))
14601 {
14602 /* Fast path */
14603 if (formatfloat(v, arg, NULL, writer) == -1)
14604 return -1;
14605 return 1;
14606 }
14607
14608 arg->sign = 1;
14609 if (formatfloat(v, arg, p_str, NULL) == -1)
14610 return -1;
14611 break;
14612
14613 case 'c':
14614 {
14615 Py_UCS4 ch = formatchar(v);
14616 if (ch == (Py_UCS4) -1)
14617 return -1;
14618 if (arg->width == -1 && arg->prec == -1) {
14619 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014620 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014621 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014622 return 1;
14623 }
14624 *p_str = PyUnicode_FromOrdinal(ch);
14625 break;
14626 }
14627
14628 default:
14629 PyErr_Format(PyExc_ValueError,
14630 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014631 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014632 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14633 (int)arg->ch,
14634 ctx->fmtpos - 1);
14635 return -1;
14636 }
14637 if (*p_str == NULL)
14638 return -1;
14639 assert (PyUnicode_Check(*p_str));
14640 return 0;
14641}
14642
14643static int
14644unicode_format_arg_output(struct unicode_formatter_t *ctx,
14645 struct unicode_format_arg_t *arg,
14646 PyObject *str)
14647{
14648 Py_ssize_t len;
14649 enum PyUnicode_Kind kind;
14650 void *pbuf;
14651 Py_ssize_t pindex;
14652 Py_UCS4 signchar;
14653 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014654 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014655 Py_ssize_t sublen;
14656 _PyUnicodeWriter *writer = &ctx->writer;
14657 Py_UCS4 fill;
14658
14659 fill = ' ';
14660 if (arg->sign && arg->flags & F_ZERO)
14661 fill = '0';
14662
14663 if (PyUnicode_READY(str) == -1)
14664 return -1;
14665
14666 len = PyUnicode_GET_LENGTH(str);
14667 if ((arg->width == -1 || arg->width <= len)
14668 && (arg->prec == -1 || arg->prec >= len)
14669 && !(arg->flags & (F_SIGN | F_BLANK)))
14670 {
14671 /* Fast path */
14672 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14673 return -1;
14674 return 0;
14675 }
14676
14677 /* Truncate the string for "s", "r" and "a" formats
14678 if the precision is set */
14679 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14680 if (arg->prec >= 0 && len > arg->prec)
14681 len = arg->prec;
14682 }
14683
14684 /* Adjust sign and width */
14685 kind = PyUnicode_KIND(str);
14686 pbuf = PyUnicode_DATA(str);
14687 pindex = 0;
14688 signchar = '\0';
14689 if (arg->sign) {
14690 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14691 if (ch == '-' || ch == '+') {
14692 signchar = ch;
14693 len--;
14694 pindex++;
14695 }
14696 else if (arg->flags & F_SIGN)
14697 signchar = '+';
14698 else if (arg->flags & F_BLANK)
14699 signchar = ' ';
14700 else
14701 arg->sign = 0;
14702 }
14703 if (arg->width < len)
14704 arg->width = len;
14705
14706 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014707 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014708 if (!(arg->flags & F_LJUST)) {
14709 if (arg->sign) {
14710 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014711 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014712 }
14713 else {
14714 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014715 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014716 }
14717 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014718 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14719 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014720 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014721 }
14722
Victor Stinnera47082312012-10-04 02:19:54 +020014723 buflen = arg->width;
14724 if (arg->sign && len == arg->width)
14725 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014726 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014727 return -1;
14728
14729 /* Write the sign if needed */
14730 if (arg->sign) {
14731 if (fill != ' ') {
14732 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14733 writer->pos += 1;
14734 }
14735 if (arg->width > len)
14736 arg->width--;
14737 }
14738
14739 /* Write the numeric prefix for "x", "X" and "o" formats
14740 if the alternate form is used.
14741 For example, write "0x" for the "%#x" format. */
14742 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14743 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14744 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14745 if (fill != ' ') {
14746 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14747 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14748 writer->pos += 2;
14749 pindex += 2;
14750 }
14751 arg->width -= 2;
14752 if (arg->width < 0)
14753 arg->width = 0;
14754 len -= 2;
14755 }
14756
14757 /* Pad left with the fill character if needed */
14758 if (arg->width > len && !(arg->flags & F_LJUST)) {
14759 sublen = arg->width - len;
14760 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14761 writer->pos += sublen;
14762 arg->width = len;
14763 }
14764
14765 /* If padding with spaces: write sign if needed and/or numeric prefix if
14766 the alternate form is used */
14767 if (fill == ' ') {
14768 if (arg->sign) {
14769 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14770 writer->pos += 1;
14771 }
14772 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14773 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14774 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14775 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14776 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14777 writer->pos += 2;
14778 pindex += 2;
14779 }
14780 }
14781
14782 /* Write characters */
14783 if (len) {
14784 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14785 str, pindex, len);
14786 writer->pos += len;
14787 }
14788
14789 /* Pad right with the fill character if needed */
14790 if (arg->width > len) {
14791 sublen = arg->width - len;
14792 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14793 writer->pos += sublen;
14794 }
14795 return 0;
14796}
14797
14798/* Helper of PyUnicode_Format(): format one arg.
14799 Return 0 on success, raise an exception and return -1 on error. */
14800static int
14801unicode_format_arg(struct unicode_formatter_t *ctx)
14802{
14803 struct unicode_format_arg_t arg;
14804 PyObject *str;
14805 int ret;
14806
Victor Stinner8dbd4212012-12-04 09:30:24 +010014807 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014808 if (arg.ch == '%') {
14809 ctx->fmtpos++;
14810 ctx->fmtcnt--;
14811 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14812 return -1;
14813 return 0;
14814 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014815 arg.flags = 0;
14816 arg.width = -1;
14817 arg.prec = -1;
14818 arg.sign = 0;
14819 str = NULL;
14820
Victor Stinnera47082312012-10-04 02:19:54 +020014821 ret = unicode_format_arg_parse(ctx, &arg);
14822 if (ret == -1)
14823 return -1;
14824
14825 ret = unicode_format_arg_format(ctx, &arg, &str);
14826 if (ret == -1)
14827 return -1;
14828
14829 if (ret != 1) {
14830 ret = unicode_format_arg_output(ctx, &arg, str);
14831 Py_DECREF(str);
14832 if (ret == -1)
14833 return -1;
14834 }
14835
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014836 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014837 PyErr_SetString(PyExc_TypeError,
14838 "not all arguments converted during string formatting");
14839 return -1;
14840 }
14841 return 0;
14842}
14843
Alexander Belopolsky40018472011-02-26 01:02:56 +000014844PyObject *
14845PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014846{
Victor Stinnera47082312012-10-04 02:19:54 +020014847 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014848
Guido van Rossumd57fd912000-03-10 22:53:23 +000014849 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014850 PyErr_BadInternalCall();
14851 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014852 }
Victor Stinnera47082312012-10-04 02:19:54 +020014853
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014854 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014855 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014856
14857 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014858 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14859 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14860 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14861 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014862
Victor Stinner8f674cc2013-04-17 23:02:17 +020014863 _PyUnicodeWriter_Init(&ctx.writer);
14864 ctx.writer.min_length = ctx.fmtcnt + 100;
14865 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014866
Guido van Rossumd57fd912000-03-10 22:53:23 +000014867 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014868 ctx.arglen = PyTuple_Size(args);
14869 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014870 }
14871 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014872 ctx.arglen = -1;
14873 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014874 }
Victor Stinnera47082312012-10-04 02:19:54 +020014875 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014876 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014877 ctx.dict = args;
14878 else
14879 ctx.dict = NULL;
14880 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014881
Victor Stinnera47082312012-10-04 02:19:54 +020014882 while (--ctx.fmtcnt >= 0) {
14883 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014884 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014885
14886 nonfmtpos = ctx.fmtpos++;
14887 while (ctx.fmtcnt >= 0 &&
14888 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14889 ctx.fmtpos++;
14890 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014891 }
Victor Stinnera47082312012-10-04 02:19:54 +020014892 if (ctx.fmtcnt < 0) {
14893 ctx.fmtpos--;
14894 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014895 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014896
Victor Stinnercfc4c132013-04-03 01:48:39 +020014897 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14898 nonfmtpos, ctx.fmtpos) < 0)
14899 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014900 }
14901 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014902 ctx.fmtpos++;
14903 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014904 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014905 }
14906 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014907
Victor Stinnera47082312012-10-04 02:19:54 +020014908 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014909 PyErr_SetString(PyExc_TypeError,
14910 "not all arguments converted during string formatting");
14911 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014912 }
14913
Victor Stinnera47082312012-10-04 02:19:54 +020014914 if (ctx.args_owned) {
14915 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014916 }
Victor Stinnera47082312012-10-04 02:19:54 +020014917 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014918
Benjamin Peterson29060642009-01-31 22:14:21 +000014919 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014920 _PyUnicodeWriter_Dealloc(&ctx.writer);
14921 if (ctx.args_owned) {
14922 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014923 }
14924 return NULL;
14925}
14926
Jeremy Hylton938ace62002-07-17 16:30:39 +000014927static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014928unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14929
Tim Peters6d6c1a32001-08-02 04:15:00 +000014930static PyObject *
14931unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14932{
Benjamin Peterson29060642009-01-31 22:14:21 +000014933 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014934 static char *kwlist[] = {"object", "encoding", "errors", 0};
14935 char *encoding = NULL;
14936 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014937
Benjamin Peterson14339b62009-01-31 16:36:08 +000014938 if (type != &PyUnicode_Type)
14939 return unicode_subtype_new(type, args, kwds);
14940 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014941 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014942 return NULL;
14943 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014944 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014945 if (encoding == NULL && errors == NULL)
14946 return PyObject_Str(x);
14947 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014948 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014949}
14950
Guido van Rossume023fe02001-08-30 03:12:59 +000014951static PyObject *
14952unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14953{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014954 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014955 Py_ssize_t length, char_size;
14956 int share_wstr, share_utf8;
14957 unsigned int kind;
14958 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014959
Benjamin Peterson14339b62009-01-31 16:36:08 +000014960 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014961
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014962 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014963 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014964 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014965 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014966 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014967 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014968 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014969 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014970
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014971 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014972 if (self == NULL) {
14973 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014974 return NULL;
14975 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014976 kind = PyUnicode_KIND(unicode);
14977 length = PyUnicode_GET_LENGTH(unicode);
14978
14979 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014980#ifdef Py_DEBUG
14981 _PyUnicode_HASH(self) = -1;
14982#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014983 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014984#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014985 _PyUnicode_STATE(self).interned = 0;
14986 _PyUnicode_STATE(self).kind = kind;
14987 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014988 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014989 _PyUnicode_STATE(self).ready = 1;
14990 _PyUnicode_WSTR(self) = NULL;
14991 _PyUnicode_UTF8_LENGTH(self) = 0;
14992 _PyUnicode_UTF8(self) = NULL;
14993 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014994 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014995
14996 share_utf8 = 0;
14997 share_wstr = 0;
14998 if (kind == PyUnicode_1BYTE_KIND) {
14999 char_size = 1;
15000 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15001 share_utf8 = 1;
15002 }
15003 else if (kind == PyUnicode_2BYTE_KIND) {
15004 char_size = 2;
15005 if (sizeof(wchar_t) == 2)
15006 share_wstr = 1;
15007 }
15008 else {
15009 assert(kind == PyUnicode_4BYTE_KIND);
15010 char_size = 4;
15011 if (sizeof(wchar_t) == 4)
15012 share_wstr = 1;
15013 }
15014
15015 /* Ensure we won't overflow the length. */
15016 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15017 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015018 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015019 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015020 data = PyObject_MALLOC((length + 1) * char_size);
15021 if (data == NULL) {
15022 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015023 goto onError;
15024 }
15025
Victor Stinnerc3c74152011-10-02 20:39:55 +020015026 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015027 if (share_utf8) {
15028 _PyUnicode_UTF8_LENGTH(self) = length;
15029 _PyUnicode_UTF8(self) = data;
15030 }
15031 if (share_wstr) {
15032 _PyUnicode_WSTR_LENGTH(self) = length;
15033 _PyUnicode_WSTR(self) = (wchar_t *)data;
15034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015035
Christian Heimesf051e432016-09-13 20:22:02 +020015036 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015037 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015038 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015039#ifdef Py_DEBUG
15040 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15041#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015042 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015043 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015044
15045onError:
15046 Py_DECREF(unicode);
15047 Py_DECREF(self);
15048 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015049}
15050
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015051PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015052"str(object='') -> str\n\
15053str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015054\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015055Create a new string object from the given object. If encoding or\n\
15056errors is specified, then the object must expose a data buffer\n\
15057that will be decoded using the given encoding and error handler.\n\
15058Otherwise, returns the result of object.__str__() (if defined)\n\
15059or repr(object).\n\
15060encoding defaults to sys.getdefaultencoding().\n\
15061errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015062
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015063static PyObject *unicode_iter(PyObject *seq);
15064
Guido van Rossumd57fd912000-03-10 22:53:23 +000015065PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015066 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015067 "str", /* tp_name */
15068 sizeof(PyUnicodeObject), /* tp_size */
15069 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015070 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 (destructor)unicode_dealloc, /* tp_dealloc */
15072 0, /* tp_print */
15073 0, /* tp_getattr */
15074 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015075 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015076 unicode_repr, /* tp_repr */
15077 &unicode_as_number, /* tp_as_number */
15078 &unicode_as_sequence, /* tp_as_sequence */
15079 &unicode_as_mapping, /* tp_as_mapping */
15080 (hashfunc) unicode_hash, /* tp_hash*/
15081 0, /* tp_call*/
15082 (reprfunc) unicode_str, /* tp_str */
15083 PyObject_GenericGetAttr, /* tp_getattro */
15084 0, /* tp_setattro */
15085 0, /* tp_as_buffer */
15086 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015087 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015088 unicode_doc, /* tp_doc */
15089 0, /* tp_traverse */
15090 0, /* tp_clear */
15091 PyUnicode_RichCompare, /* tp_richcompare */
15092 0, /* tp_weaklistoffset */
15093 unicode_iter, /* tp_iter */
15094 0, /* tp_iternext */
15095 unicode_methods, /* tp_methods */
15096 0, /* tp_members */
15097 0, /* tp_getset */
15098 &PyBaseObject_Type, /* tp_base */
15099 0, /* tp_dict */
15100 0, /* tp_descr_get */
15101 0, /* tp_descr_set */
15102 0, /* tp_dictoffset */
15103 0, /* tp_init */
15104 0, /* tp_alloc */
15105 unicode_new, /* tp_new */
15106 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015107};
15108
15109/* Initialize the Unicode implementation */
15110
Victor Stinner3a50e702011-10-18 21:21:00 +020015111int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015112{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015113 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015114 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015115 0x000A, /* LINE FEED */
15116 0x000D, /* CARRIAGE RETURN */
15117 0x001C, /* FILE SEPARATOR */
15118 0x001D, /* GROUP SEPARATOR */
15119 0x001E, /* RECORD SEPARATOR */
15120 0x0085, /* NEXT LINE */
15121 0x2028, /* LINE SEPARATOR */
15122 0x2029, /* PARAGRAPH SEPARATOR */
15123 };
15124
Fred Drakee4315f52000-05-09 19:53:39 +000015125 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015126 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015127 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015128 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015129 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015130
Guido van Rossumcacfc072002-05-24 19:01:59 +000015131 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015132 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015133
15134 /* initialize the linebreak bloom filter */
15135 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015136 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015137 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015138
Christian Heimes26532f72013-07-20 14:57:16 +020015139 if (PyType_Ready(&EncodingMapType) < 0)
15140 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015141
Benjamin Petersonc4311282012-10-30 23:21:10 -040015142 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15143 Py_FatalError("Can't initialize field name iterator type");
15144
15145 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15146 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015147
Victor Stinner3a50e702011-10-18 21:21:00 +020015148 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015149}
15150
15151/* Finalize the Unicode implementation */
15152
Christian Heimesa156e092008-02-16 07:38:31 +000015153int
15154PyUnicode_ClearFreeList(void)
15155{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015156 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015157}
15158
Guido van Rossumd57fd912000-03-10 22:53:23 +000015159void
Thomas Wouters78890102000-07-22 19:25:51 +000015160_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015161{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015162 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015163
Serhiy Storchaka05997252013-01-26 12:14:02 +020015164 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015165
Serhiy Storchaka05997252013-01-26 12:14:02 +020015166 for (i = 0; i < 256; i++)
15167 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015168 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015169 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015170}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015171
Walter Dörwald16807132007-05-25 13:52:07 +000015172void
15173PyUnicode_InternInPlace(PyObject **p)
15174{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015175 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015176 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015177#ifdef Py_DEBUG
15178 assert(s != NULL);
15179 assert(_PyUnicode_CHECK(s));
15180#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015181 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015182 return;
15183#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015184 /* If it's a subclass, we don't really know what putting
15185 it in the interned dict might do. */
15186 if (!PyUnicode_CheckExact(s))
15187 return;
15188 if (PyUnicode_CHECK_INTERNED(s))
15189 return;
15190 if (interned == NULL) {
15191 interned = PyDict_New();
15192 if (interned == NULL) {
15193 PyErr_Clear(); /* Don't leave an exception */
15194 return;
15195 }
15196 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015197 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015198 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015199 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015200 if (t == NULL) {
15201 PyErr_Clear();
15202 return;
15203 }
15204 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015205 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015206 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015207 return;
15208 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015209 /* The two references in interned are not counted by refcnt.
15210 The deallocator will take care of this */
15211 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015212 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015213}
15214
15215void
15216PyUnicode_InternImmortal(PyObject **p)
15217{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015218 PyUnicode_InternInPlace(p);
15219 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015220 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015221 Py_INCREF(*p);
15222 }
Walter Dörwald16807132007-05-25 13:52:07 +000015223}
15224
15225PyObject *
15226PyUnicode_InternFromString(const char *cp)
15227{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015228 PyObject *s = PyUnicode_FromString(cp);
15229 if (s == NULL)
15230 return NULL;
15231 PyUnicode_InternInPlace(&s);
15232 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015233}
15234
Alexander Belopolsky40018472011-02-26 01:02:56 +000015235void
15236_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015237{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015238 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015239 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015240 Py_ssize_t i, n;
15241 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015242
Benjamin Peterson14339b62009-01-31 16:36:08 +000015243 if (interned == NULL || !PyDict_Check(interned))
15244 return;
15245 keys = PyDict_Keys(interned);
15246 if (keys == NULL || !PyList_Check(keys)) {
15247 PyErr_Clear();
15248 return;
15249 }
Walter Dörwald16807132007-05-25 13:52:07 +000015250
Benjamin Peterson14339b62009-01-31 16:36:08 +000015251 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15252 detector, interned unicode strings are not forcibly deallocated;
15253 rather, we give them their stolen references back, and then clear
15254 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015255
Benjamin Peterson14339b62009-01-31 16:36:08 +000015256 n = PyList_GET_SIZE(keys);
15257 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015258 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015260 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015261 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015262 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015264 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015265 case SSTATE_NOT_INTERNED:
15266 /* XXX Shouldn't happen */
15267 break;
15268 case SSTATE_INTERNED_IMMORTAL:
15269 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015270 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015271 break;
15272 case SSTATE_INTERNED_MORTAL:
15273 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015274 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015275 break;
15276 default:
15277 Py_FatalError("Inconsistent interned string state.");
15278 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015279 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015280 }
15281 fprintf(stderr, "total size of all interned strings: "
15282 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15283 "mortal/immortal\n", mortal_size, immortal_size);
15284 Py_DECREF(keys);
15285 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015286 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015287}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015288
15289
15290/********************* Unicode Iterator **************************/
15291
15292typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015293 PyObject_HEAD
15294 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015295 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015296} unicodeiterobject;
15297
15298static void
15299unicodeiter_dealloc(unicodeiterobject *it)
15300{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015301 _PyObject_GC_UNTRACK(it);
15302 Py_XDECREF(it->it_seq);
15303 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015304}
15305
15306static int
15307unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15308{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015309 Py_VISIT(it->it_seq);
15310 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015311}
15312
15313static PyObject *
15314unicodeiter_next(unicodeiterobject *it)
15315{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015316 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015317
Benjamin Peterson14339b62009-01-31 16:36:08 +000015318 assert(it != NULL);
15319 seq = it->it_seq;
15320 if (seq == NULL)
15321 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015322 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015324 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15325 int kind = PyUnicode_KIND(seq);
15326 void *data = PyUnicode_DATA(seq);
15327 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15328 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015329 if (item != NULL)
15330 ++it->it_index;
15331 return item;
15332 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015333
Benjamin Peterson14339b62009-01-31 16:36:08 +000015334 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015335 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015336 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015337}
15338
15339static PyObject *
15340unicodeiter_len(unicodeiterobject *it)
15341{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015342 Py_ssize_t len = 0;
15343 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015344 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015345 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015346}
15347
15348PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15349
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015350static PyObject *
15351unicodeiter_reduce(unicodeiterobject *it)
15352{
15353 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015354 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015355 it->it_seq, it->it_index);
15356 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015357 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015358 if (u == NULL)
15359 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015360 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015361 }
15362}
15363
15364PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15365
15366static PyObject *
15367unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15368{
15369 Py_ssize_t index = PyLong_AsSsize_t(state);
15370 if (index == -1 && PyErr_Occurred())
15371 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015372 if (it->it_seq != NULL) {
15373 if (index < 0)
15374 index = 0;
15375 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15376 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15377 it->it_index = index;
15378 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015379 Py_RETURN_NONE;
15380}
15381
15382PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15383
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015384static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015385 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015386 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015387 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15388 reduce_doc},
15389 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15390 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015391 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015392};
15393
15394PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015395 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15396 "str_iterator", /* tp_name */
15397 sizeof(unicodeiterobject), /* tp_basicsize */
15398 0, /* tp_itemsize */
15399 /* methods */
15400 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15401 0, /* tp_print */
15402 0, /* tp_getattr */
15403 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015404 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015405 0, /* tp_repr */
15406 0, /* tp_as_number */
15407 0, /* tp_as_sequence */
15408 0, /* tp_as_mapping */
15409 0, /* tp_hash */
15410 0, /* tp_call */
15411 0, /* tp_str */
15412 PyObject_GenericGetAttr, /* tp_getattro */
15413 0, /* tp_setattro */
15414 0, /* tp_as_buffer */
15415 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15416 0, /* tp_doc */
15417 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15418 0, /* tp_clear */
15419 0, /* tp_richcompare */
15420 0, /* tp_weaklistoffset */
15421 PyObject_SelfIter, /* tp_iter */
15422 (iternextfunc)unicodeiter_next, /* tp_iternext */
15423 unicodeiter_methods, /* tp_methods */
15424 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015425};
15426
15427static PyObject *
15428unicode_iter(PyObject *seq)
15429{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015430 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015431
Benjamin Peterson14339b62009-01-31 16:36:08 +000015432 if (!PyUnicode_Check(seq)) {
15433 PyErr_BadInternalCall();
15434 return NULL;
15435 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015436 if (PyUnicode_READY(seq) == -1)
15437 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015438 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15439 if (it == NULL)
15440 return NULL;
15441 it->it_index = 0;
15442 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015443 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015444 _PyObject_GC_TRACK(it);
15445 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015446}
15447
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015448
15449size_t
15450Py_UNICODE_strlen(const Py_UNICODE *u)
15451{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015452 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015453}
15454
15455Py_UNICODE*
15456Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15457{
15458 Py_UNICODE *u = s1;
15459 while ((*u++ = *s2++));
15460 return s1;
15461}
15462
15463Py_UNICODE*
15464Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15465{
15466 Py_UNICODE *u = s1;
15467 while ((*u++ = *s2++))
15468 if (n-- == 0)
15469 break;
15470 return s1;
15471}
15472
15473Py_UNICODE*
15474Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15475{
15476 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015477 u1 += wcslen(u1);
15478 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015479 return s1;
15480}
15481
15482int
15483Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15484{
15485 while (*s1 && *s2 && *s1 == *s2)
15486 s1++, s2++;
15487 if (*s1 && *s2)
15488 return (*s1 < *s2) ? -1 : +1;
15489 if (*s1)
15490 return 1;
15491 if (*s2)
15492 return -1;
15493 return 0;
15494}
15495
15496int
15497Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15498{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015499 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015500 for (; n != 0; n--) {
15501 u1 = *s1;
15502 u2 = *s2;
15503 if (u1 != u2)
15504 return (u1 < u2) ? -1 : +1;
15505 if (u1 == '\0')
15506 return 0;
15507 s1++;
15508 s2++;
15509 }
15510 return 0;
15511}
15512
15513Py_UNICODE*
15514Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15515{
15516 const Py_UNICODE *p;
15517 for (p = s; *p; p++)
15518 if (*p == c)
15519 return (Py_UNICODE*)p;
15520 return NULL;
15521}
15522
15523Py_UNICODE*
15524Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15525{
15526 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015527 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015528 while (p != s) {
15529 p--;
15530 if (*p == c)
15531 return (Py_UNICODE*)p;
15532 }
15533 return NULL;
15534}
Victor Stinner331ea922010-08-10 16:37:20 +000015535
Victor Stinner71133ff2010-09-01 23:43:53 +000015536Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015537PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015538{
Victor Stinner577db2c2011-10-11 22:12:48 +020015539 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015540 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015542 if (!PyUnicode_Check(unicode)) {
15543 PyErr_BadArgument();
15544 return NULL;
15545 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015546 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015547 if (u == NULL)
15548 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015549 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015550 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015551 PyErr_NoMemory();
15552 return NULL;
15553 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015554 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015555 size *= sizeof(Py_UNICODE);
15556 copy = PyMem_Malloc(size);
15557 if (copy == NULL) {
15558 PyErr_NoMemory();
15559 return NULL;
15560 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015561 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015562 return copy;
15563}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015564
Georg Brandl66c221e2010-10-14 07:04:07 +000015565/* A _string module, to export formatter_parser and formatter_field_name_split
15566 to the string.Formatter class implemented in Python. */
15567
15568static PyMethodDef _string_methods[] = {
15569 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15570 METH_O, PyDoc_STR("split the argument as a field name")},
15571 {"formatter_parser", (PyCFunction) formatter_parser,
15572 METH_O, PyDoc_STR("parse the argument as a format string")},
15573 {NULL, NULL}
15574};
15575
15576static struct PyModuleDef _string_module = {
15577 PyModuleDef_HEAD_INIT,
15578 "_string",
15579 PyDoc_STR("string helper module"),
15580 0,
15581 _string_methods,
15582 NULL,
15583 NULL,
15584 NULL,
15585 NULL
15586};
15587
15588PyMODINIT_FUNC
15589PyInit__string(void)
15590{
15591 return PyModule_Create(&_string_module);
15592}
15593
15594
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015595#ifdef __cplusplus
15596}
15597#endif