blob: 0460d184932ee02f5498c6bd56d17e7fd19a4f76 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043#include "internal/pystate.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000044#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050045#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070046#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000047
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000048#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000049#include <windows.h>
50#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000051
Larry Hastings61272b72014-01-07 12:41:53 -080052/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090053class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080054[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090055/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
56
57/*[python input]
58class Py_UCS4_converter(CConverter):
59 type = 'Py_UCS4'
60 converter = 'convert_uc'
61
62 def converter_init(self):
63 if self.default is not unspecified:
64 self.c_default = ascii(self.default)
65 if len(self.c_default) > 4 or self.c_default[0] != "'":
66 self.c_default = hex(ord(self.default))
67
68[python start generated code]*/
69/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080070
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000071/* --- Globals ------------------------------------------------------------
72
Serhiy Storchaka05997252013-01-26 12:14:02 +020073NOTE: In the interpreter's initialization phase, some globals are currently
74 initialized dynamically as needed. In the process Unicode objects may
75 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000076
77*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000078
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079
80#ifdef __cplusplus
81extern "C" {
82#endif
83
Victor Stinner8faf8212011-12-08 22:14:11 +010084/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
85#define MAX_UNICODE 0x10ffff
86
Victor Stinner910337b2011-10-03 03:20:16 +020087#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020088# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020089#else
90# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
91#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020092
Victor Stinnere90fe6a2011-10-01 16:48:13 +020093#define _PyUnicode_UTF8(op) \
94 (((PyCompactUnicodeObject*)(op))->utf8)
95#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020096 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020097 assert(PyUnicode_IS_READY(op)), \
98 PyUnicode_IS_COMPACT_ASCII(op) ? \
99 ((char*)((PyASCIIObject*)(op) + 1)) : \
100 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200101#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102 (((PyCompactUnicodeObject*)(op))->utf8_length)
103#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200104 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200105 assert(PyUnicode_IS_READY(op)), \
106 PyUnicode_IS_COMPACT_ASCII(op) ? \
107 ((PyASCIIObject*)(op))->length : \
108 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_WSTR(op) \
110 (((PyASCIIObject*)(op))->wstr)
111#define _PyUnicode_WSTR_LENGTH(op) \
112 (((PyCompactUnicodeObject*)(op))->wstr_length)
113#define _PyUnicode_LENGTH(op) \
114 (((PyASCIIObject *)(op))->length)
115#define _PyUnicode_STATE(op) \
116 (((PyASCIIObject *)(op))->state)
117#define _PyUnicode_HASH(op) \
118 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200119#define _PyUnicode_KIND(op) \
120 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200121 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200122#define _PyUnicode_GET_LENGTH(op) \
123 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200124 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200125#define _PyUnicode_DATA_ANY(op) \
126 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200127
Victor Stinner910337b2011-10-03 03:20:16 +0200128#undef PyUnicode_READY
129#define PyUnicode_READY(op) \
130 (assert(_PyUnicode_CHECK(op)), \
131 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200132 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100133 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200134
Victor Stinnerc379ead2011-10-03 12:52:27 +0200135#define _PyUnicode_SHARE_UTF8(op) \
136 (assert(_PyUnicode_CHECK(op)), \
137 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
138 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
139#define _PyUnicode_SHARE_WSTR(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
142
Victor Stinner829c0ad2011-10-03 01:08:02 +0200143/* true if the Unicode object has an allocated UTF-8 memory block
144 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200145#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200146 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200147 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200148 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
149
Victor Stinner03490912011-10-03 23:45:12 +0200150/* true if the Unicode object has an allocated wstr memory block
151 (not shared with other data) */
152#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200153 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200154 (!PyUnicode_IS_READY(op) || \
155 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
156
Victor Stinner910337b2011-10-03 03:20:16 +0200157/* Generic helper macro to convert characters of different types.
158 from_type and to_type have to be valid type names, begin and end
159 are pointers to the source characters which should be of type
160 "from_type *". to is a pointer of type "to_type *" and points to the
161 buffer where the result characters are written to. */
162#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
163 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100164 to_type *_to = (to_type *)(to); \
165 const from_type *_iter = (from_type *)(begin); \
166 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200167 Py_ssize_t n = (_end) - (_iter); \
168 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200169 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_unrolled_end)) { \
171 _to[0] = (to_type) _iter[0]; \
172 _to[1] = (to_type) _iter[1]; \
173 _to[2] = (to_type) _iter[2]; \
174 _to[3] = (to_type) _iter[3]; \
175 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200176 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200177 while (_iter < (_end)) \
178 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200179 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200180
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200181#ifdef MS_WINDOWS
182 /* On Windows, overallocate by 50% is the best factor */
183# define OVERALLOCATE_FACTOR 2
184#else
185 /* On Linux, overallocate by 25% is the best factor */
186# define OVERALLOCATE_FACTOR 4
187#endif
188
Walter Dörwald16807132007-05-25 13:52:07 +0000189/* This dictionary holds all interned unicode strings. Note that references
190 to strings in this dictionary are *not* counted in the string's ob_refcnt.
191 When the interned string reaches a refcnt of 0 the string deallocation
192 function will delete the reference from this dictionary.
193
194 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000195 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000196*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000198
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200201
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200203 do { \
204 if (unicode_empty != NULL) \
205 Py_INCREF(unicode_empty); \
206 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207 unicode_empty = PyUnicode_New(0, 0); \
208 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200209 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200210 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
211 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200212 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200213 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000214
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215#define _Py_RETURN_UNICODE_EMPTY() \
216 do { \
217 _Py_INCREF_UNICODE_EMPTY(); \
218 return unicode_empty; \
219 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000220
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200221/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700222static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200223_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
224
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200225/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200226static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200227
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000228/* Single character Unicode strings in the Latin-1 range are being
229 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200230static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000231
Christian Heimes190d79e2008-01-30 11:58:22 +0000232/* Fast detection of the most frequent whitespace characters */
233const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000234 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000235/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000236/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000237/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000238/* case 0x000C: * FORM FEED */
239/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000240 0, 1, 1, 1, 1, 1, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000242/* case 0x001C: * FILE SEPARATOR */
243/* case 0x001D: * GROUP SEPARATOR */
244/* case 0x001E: * RECORD SEPARATOR */
245/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000246 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000247/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000248 1, 0, 0, 0, 0, 0, 0, 0,
249 0, 0, 0, 0, 0, 0, 0, 0,
250 0, 0, 0, 0, 0, 0, 0, 0,
251 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000252
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
254 0, 0, 0, 0, 0, 0, 0, 0,
255 0, 0, 0, 0, 0, 0, 0, 0,
256 0, 0, 0, 0, 0, 0, 0, 0,
257 0, 0, 0, 0, 0, 0, 0, 0,
258 0, 0, 0, 0, 0, 0, 0, 0,
259 0, 0, 0, 0, 0, 0, 0, 0,
260 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000261};
262
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200263/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200264static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200265static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100266static int unicode_modifiable(PyObject *unicode);
267
Victor Stinnerfe226c02011-10-03 03:52:20 +0200268
Alexander Belopolsky40018472011-02-26 01:02:56 +0000269static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100270_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200271static PyObject *
272_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
273static PyObject *
274_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
275
276static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000277unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000278 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100279 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000280 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
281
Alexander Belopolsky40018472011-02-26 01:02:56 +0000282static void
283raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300284 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100285 PyObject *unicode,
286 Py_ssize_t startpos, Py_ssize_t endpos,
287 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000288
Christian Heimes190d79e2008-01-30 11:58:22 +0000289/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200290static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000291 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000292/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000293/* 0x000B, * LINE TABULATION */
294/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000295/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000296 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000298/* 0x001C, * FILE SEPARATOR */
299/* 0x001D, * GROUP SEPARATOR */
300/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 0, 0, 0, 0, 1, 1, 1, 0,
302 0, 0, 0, 0, 0, 0, 0, 0,
303 0, 0, 0, 0, 0, 0, 0, 0,
304 0, 0, 0, 0, 0, 0, 0, 0,
305 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000306
Benjamin Peterson14339b62009-01-31 16:36:08 +0000307 0, 0, 0, 0, 0, 0, 0, 0,
308 0, 0, 0, 0, 0, 0, 0, 0,
309 0, 0, 0, 0, 0, 0, 0, 0,
310 0, 0, 0, 0, 0, 0, 0, 0,
311 0, 0, 0, 0, 0, 0, 0, 0,
312 0, 0, 0, 0, 0, 0, 0, 0,
313 0, 0, 0, 0, 0, 0, 0, 0,
314 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000315};
316
INADA Naoki3ae20562017-01-16 20:41:20 +0900317static int convert_uc(PyObject *obj, void *addr);
318
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300319#include "clinic/unicodeobject.c.h"
320
Victor Stinner50149202015-09-22 00:26:54 +0200321typedef enum {
322 _Py_ERROR_UNKNOWN=0,
323 _Py_ERROR_STRICT,
324 _Py_ERROR_SURROGATEESCAPE,
325 _Py_ERROR_REPLACE,
326 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200327 _Py_ERROR_BACKSLASHREPLACE,
328 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200329 _Py_ERROR_XMLCHARREFREPLACE,
330 _Py_ERROR_OTHER
331} _Py_error_handler;
332
333static _Py_error_handler
334get_error_handler(const char *errors)
335{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200337 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200338 }
339 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200341 }
342 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200343 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200344 }
345 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200346 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200347 }
348 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200349 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200350 }
351 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200352 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200353 }
354 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200355 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200356 }
Victor Stinner50149202015-09-22 00:26:54 +0200357 return _Py_ERROR_OTHER;
358}
359
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300360/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
361 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000362Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000363PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000364{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000365#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000366 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000367#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000368 /* This is actually an illegal character, so it should
369 not be passed to unichr. */
370 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000371#endif
372}
373
Victor Stinner910337b2011-10-03 03:20:16 +0200374#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200375int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100376_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200377{
378 PyASCIIObject *ascii;
379 unsigned int kind;
380
381 assert(PyUnicode_Check(op));
382
383 ascii = (PyASCIIObject *)op;
384 kind = ascii->state.kind;
385
Victor Stinnera3b334d2011-10-03 13:53:37 +0200386 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200387 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200388 assert(ascii->state.ready == 1);
389 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200390 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200391 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200392 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200393
Victor Stinnera41463c2011-10-04 01:05:08 +0200394 if (ascii->state.compact == 1) {
395 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200396 assert(kind == PyUnicode_1BYTE_KIND
397 || kind == PyUnicode_2BYTE_KIND
398 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200399 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200400 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200401 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100402 }
403 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200404 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
405
406 data = unicode->data.any;
407 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100408 assert(ascii->length == 0);
409 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200410 assert(ascii->state.compact == 0);
411 assert(ascii->state.ascii == 0);
412 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100413 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200414 assert(ascii->wstr != NULL);
415 assert(data == NULL);
416 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200417 }
418 else {
419 assert(kind == PyUnicode_1BYTE_KIND
420 || kind == PyUnicode_2BYTE_KIND
421 || kind == PyUnicode_4BYTE_KIND);
422 assert(ascii->state.compact == 0);
423 assert(ascii->state.ready == 1);
424 assert(data != NULL);
425 if (ascii->state.ascii) {
426 assert (compact->utf8 == data);
427 assert (compact->utf8_length == ascii->length);
428 }
429 else
430 assert (compact->utf8 != data);
431 }
432 }
433 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200434 if (
435#if SIZEOF_WCHAR_T == 2
436 kind == PyUnicode_2BYTE_KIND
437#else
438 kind == PyUnicode_4BYTE_KIND
439#endif
440 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200441 {
442 assert(ascii->wstr == data);
443 assert(compact->wstr_length == ascii->length);
444 } else
445 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200446 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200447
448 if (compact->utf8 == NULL)
449 assert(compact->utf8_length == 0);
450 if (ascii->wstr == NULL)
451 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200452 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 /* check that the best kind is used */
454 if (check_content && kind != PyUnicode_WCHAR_KIND)
455 {
456 Py_ssize_t i;
457 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200458 void *data;
459 Py_UCS4 ch;
460
461 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200462 for (i=0; i < ascii->length; i++)
463 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200464 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200465 if (ch > maxchar)
466 maxchar = ch;
467 }
468 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100469 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200470 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100471 assert(maxchar <= 255);
472 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200473 else
474 assert(maxchar < 128);
475 }
Victor Stinner77faf692011-11-20 18:56:05 +0100476 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200477 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100478 assert(maxchar <= 0xFFFF);
479 }
480 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200481 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100482 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100483 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200484 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200485 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400486 return 1;
487}
Victor Stinner910337b2011-10-03 03:20:16 +0200488#endif
489
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100490static PyObject*
491unicode_result_wchar(PyObject *unicode)
492{
493#ifndef Py_DEBUG
494 Py_ssize_t len;
495
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 len = _PyUnicode_WSTR_LENGTH(unicode);
497 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100498 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200499 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100500 }
501
502 if (len == 1) {
503 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100504 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100505 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
506 Py_DECREF(unicode);
507 return latin1_char;
508 }
509 }
510
511 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200512 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100513 return NULL;
514 }
515#else
Victor Stinneraa771272012-10-04 02:32:58 +0200516 assert(Py_REFCNT(unicode) == 1);
517
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 /* don't make the result ready in debug mode to ensure that the caller
519 makes the string ready before using it */
520 assert(_PyUnicode_CheckConsistency(unicode, 1));
521#endif
522 return unicode;
523}
524
525static PyObject*
526unicode_result_ready(PyObject *unicode)
527{
528 Py_ssize_t length;
529
530 length = PyUnicode_GET_LENGTH(unicode);
531 if (length == 0) {
532 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100533 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200534 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100535 }
536 return unicode_empty;
537 }
538
539 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200540 void *data = PyUnicode_DATA(unicode);
541 int kind = PyUnicode_KIND(unicode);
542 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100543 if (ch < 256) {
544 PyObject *latin1_char = unicode_latin1[ch];
545 if (latin1_char != NULL) {
546 if (unicode != latin1_char) {
547 Py_INCREF(latin1_char);
548 Py_DECREF(unicode);
549 }
550 return latin1_char;
551 }
552 else {
553 assert(_PyUnicode_CheckConsistency(unicode, 1));
554 Py_INCREF(unicode);
555 unicode_latin1[ch] = unicode;
556 return unicode;
557 }
558 }
559 }
560
561 assert(_PyUnicode_CheckConsistency(unicode, 1));
562 return unicode;
563}
564
565static PyObject*
566unicode_result(PyObject *unicode)
567{
568 assert(_PyUnicode_CHECK(unicode));
569 if (PyUnicode_IS_READY(unicode))
570 return unicode_result_ready(unicode);
571 else
572 return unicode_result_wchar(unicode);
573}
574
Victor Stinnerc4b49542011-12-11 22:44:26 +0100575static PyObject*
576unicode_result_unchanged(PyObject *unicode)
577{
578 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500579 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100580 return NULL;
581 Py_INCREF(unicode);
582 return unicode;
583 }
584 else
585 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100586 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100587}
588
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200589/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
590 ASCII, Latin1, UTF-8, etc. */
591static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200592backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200593 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
594{
Victor Stinnerad771582015-10-09 12:38:53 +0200595 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200596 Py_UCS4 ch;
597 enum PyUnicode_Kind kind;
598 void *data;
599
600 assert(PyUnicode_IS_READY(unicode));
601 kind = PyUnicode_KIND(unicode);
602 data = PyUnicode_DATA(unicode);
603
604 size = 0;
605 /* determine replacement size */
606 for (i = collstart; i < collend; ++i) {
607 Py_ssize_t incr;
608
609 ch = PyUnicode_READ(kind, data, i);
610 if (ch < 0x100)
611 incr = 2+2;
612 else if (ch < 0x10000)
613 incr = 2+4;
614 else {
615 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200616 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200617 }
618 if (size > PY_SSIZE_T_MAX - incr) {
619 PyErr_SetString(PyExc_OverflowError,
620 "encoded result is too long for a Python string");
621 return NULL;
622 }
623 size += incr;
624 }
625
Victor Stinnerad771582015-10-09 12:38:53 +0200626 str = _PyBytesWriter_Prepare(writer, str, size);
627 if (str == NULL)
628 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200629
630 /* generate replacement */
631 for (i = collstart; i < collend; ++i) {
632 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200633 *str++ = '\\';
634 if (ch >= 0x00010000) {
635 *str++ = 'U';
636 *str++ = Py_hexdigits[(ch>>28)&0xf];
637 *str++ = Py_hexdigits[(ch>>24)&0xf];
638 *str++ = Py_hexdigits[(ch>>20)&0xf];
639 *str++ = Py_hexdigits[(ch>>16)&0xf];
640 *str++ = Py_hexdigits[(ch>>12)&0xf];
641 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200642 }
Victor Stinner797485e2015-10-09 03:17:30 +0200643 else if (ch >= 0x100) {
644 *str++ = 'u';
645 *str++ = Py_hexdigits[(ch>>12)&0xf];
646 *str++ = Py_hexdigits[(ch>>8)&0xf];
647 }
648 else
649 *str++ = 'x';
650 *str++ = Py_hexdigits[(ch>>4)&0xf];
651 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200652 }
653 return str;
654}
655
656/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
657 ASCII, Latin1, UTF-8, etc. */
658static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200659xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200660 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
661{
Victor Stinnerad771582015-10-09 12:38:53 +0200662 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200663 Py_UCS4 ch;
664 enum PyUnicode_Kind kind;
665 void *data;
666
667 assert(PyUnicode_IS_READY(unicode));
668 kind = PyUnicode_KIND(unicode);
669 data = PyUnicode_DATA(unicode);
670
671 size = 0;
672 /* determine replacement size */
673 for (i = collstart; i < collend; ++i) {
674 Py_ssize_t incr;
675
676 ch = PyUnicode_READ(kind, data, i);
677 if (ch < 10)
678 incr = 2+1+1;
679 else if (ch < 100)
680 incr = 2+2+1;
681 else if (ch < 1000)
682 incr = 2+3+1;
683 else if (ch < 10000)
684 incr = 2+4+1;
685 else if (ch < 100000)
686 incr = 2+5+1;
687 else if (ch < 1000000)
688 incr = 2+6+1;
689 else {
690 assert(ch <= MAX_UNICODE);
691 incr = 2+7+1;
692 }
693 if (size > PY_SSIZE_T_MAX - incr) {
694 PyErr_SetString(PyExc_OverflowError,
695 "encoded result is too long for a Python string");
696 return NULL;
697 }
698 size += incr;
699 }
700
Victor Stinnerad771582015-10-09 12:38:53 +0200701 str = _PyBytesWriter_Prepare(writer, str, size);
702 if (str == NULL)
703 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200704
705 /* generate replacement */
706 for (i = collstart; i < collend; ++i) {
707 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
708 }
709 return str;
710}
711
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712/* --- Bloom Filters ----------------------------------------------------- */
713
714/* stuff to implement simple "bloom filters" for Unicode characters.
715 to keep things simple, we use a single bitmask, using the least 5
716 bits from each unicode characters as the bit index. */
717
718/* the linebreak mask is set up by Unicode_Init below */
719
Antoine Pitrouf068f942010-01-13 14:19:12 +0000720#if LONG_BIT >= 128
721#define BLOOM_WIDTH 128
722#elif LONG_BIT >= 64
723#define BLOOM_WIDTH 64
724#elif LONG_BIT >= 32
725#define BLOOM_WIDTH 32
726#else
727#error "LONG_BIT is smaller than 32"
728#endif
729
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730#define BLOOM_MASK unsigned long
731
Serhiy Storchaka05997252013-01-26 12:14:02 +0200732static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733
Antoine Pitrouf068f942010-01-13 14:19:12 +0000734#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735
Benjamin Peterson29060642009-01-31 22:14:21 +0000736#define BLOOM_LINEBREAK(ch) \
737 ((ch) < 128U ? ascii_linebreak[(ch)] : \
738 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000739
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700740static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200741make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742{
Victor Stinnera85af502013-04-09 21:53:54 +0200743#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
744 do { \
745 TYPE *data = (TYPE *)PTR; \
746 TYPE *end = data + LEN; \
747 Py_UCS4 ch; \
748 for (; data != end; data++) { \
749 ch = *data; \
750 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
751 } \
752 break; \
753 } while (0)
754
Thomas Wouters477c8d52006-05-27 19:21:47 +0000755 /* calculate simple bloom-style bitmask for a given unicode string */
756
Antoine Pitrouf068f942010-01-13 14:19:12 +0000757 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758
759 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200760 switch (kind) {
761 case PyUnicode_1BYTE_KIND:
762 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
763 break;
764 case PyUnicode_2BYTE_KIND:
765 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
766 break;
767 case PyUnicode_4BYTE_KIND:
768 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
769 break;
770 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700771 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200772 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000773 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200774
775#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776}
777
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300778static int
779ensure_unicode(PyObject *obj)
780{
781 if (!PyUnicode_Check(obj)) {
782 PyErr_Format(PyExc_TypeError,
783 "must be str, not %.100s",
784 Py_TYPE(obj)->tp_name);
785 return -1;
786 }
787 return PyUnicode_READY(obj);
788}
789
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200790/* Compilation of templated routines */
791
792#include "stringlib/asciilib.h"
793#include "stringlib/fastsearch.h"
794#include "stringlib/partition.h"
795#include "stringlib/split.h"
796#include "stringlib/count.h"
797#include "stringlib/find.h"
798#include "stringlib/find_max_char.h"
799#include "stringlib/localeutil.h"
800#include "stringlib/undef.h"
801
802#include "stringlib/ucs1lib.h"
803#include "stringlib/fastsearch.h"
804#include "stringlib/partition.h"
805#include "stringlib/split.h"
806#include "stringlib/count.h"
807#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300808#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200809#include "stringlib/find_max_char.h"
810#include "stringlib/localeutil.h"
811#include "stringlib/undef.h"
812
813#include "stringlib/ucs2lib.h"
814#include "stringlib/fastsearch.h"
815#include "stringlib/partition.h"
816#include "stringlib/split.h"
817#include "stringlib/count.h"
818#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300819#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200820#include "stringlib/find_max_char.h"
821#include "stringlib/localeutil.h"
822#include "stringlib/undef.h"
823
824#include "stringlib/ucs4lib.h"
825#include "stringlib/fastsearch.h"
826#include "stringlib/partition.h"
827#include "stringlib/split.h"
828#include "stringlib/count.h"
829#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300830#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200831#include "stringlib/find_max_char.h"
832#include "stringlib/localeutil.h"
833#include "stringlib/undef.h"
834
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200835#include "stringlib/unicodedefs.h"
836#include "stringlib/fastsearch.h"
837#include "stringlib/count.h"
838#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100839#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200840
Guido van Rossumd57fd912000-03-10 22:53:23 +0000841/* --- Unicode Object ----------------------------------------------------- */
842
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700843static inline Py_ssize_t
844findchar(const void *s, int kind,
845 Py_ssize_t size, Py_UCS4 ch,
846 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200847{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200848 switch (kind) {
849 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if ((Py_UCS1) ch != ch)
851 return -1;
852 if (direction > 0)
853 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
854 else
855 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200856 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200857 if ((Py_UCS2) ch != ch)
858 return -1;
859 if (direction > 0)
860 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
861 else
862 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200863 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200864 if (direction > 0)
865 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
866 else
867 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200868 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700869 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200871}
872
Victor Stinnerafffce42012-10-03 23:03:17 +0200873#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000874/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200875 earlier.
876
877 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
878 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
879 invalid character in Unicode 6.0. */
880static void
881unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
882{
883 int kind = PyUnicode_KIND(unicode);
884 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
885 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
886 if (length <= old_length)
887 return;
888 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
889}
890#endif
891
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892static PyObject*
893resize_compact(PyObject *unicode, Py_ssize_t length)
894{
895 Py_ssize_t char_size;
896 Py_ssize_t struct_size;
897 Py_ssize_t new_size;
898 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100899 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200900#ifdef Py_DEBUG
901 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
902#endif
903
Victor Stinner79891572012-05-03 13:43:07 +0200904 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200905 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100906 assert(PyUnicode_IS_COMPACT(unicode));
907
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200908 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100909 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200910 struct_size = sizeof(PyASCIIObject);
911 else
912 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200913 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200914
Victor Stinnerfe226c02011-10-03 03:52:20 +0200915 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
916 PyErr_NoMemory();
917 return NULL;
918 }
919 new_size = (struct_size + (length + 1) * char_size);
920
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200921 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
922 PyObject_DEL(_PyUnicode_UTF8(unicode));
923 _PyUnicode_UTF8(unicode) = NULL;
924 _PyUnicode_UTF8_LENGTH(unicode) = 0;
925 }
Victor Stinner84def372011-12-11 20:04:56 +0100926 _Py_DEC_REFTOTAL;
927 _Py_ForgetReference(unicode);
928
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300929 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100930 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100931 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 PyErr_NoMemory();
933 return NULL;
934 }
Victor Stinner84def372011-12-11 20:04:56 +0100935 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200936 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100937
Victor Stinnerfe226c02011-10-03 03:52:20 +0200938 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200939 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100941 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200942 _PyUnicode_WSTR_LENGTH(unicode) = length;
943 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100944 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
945 PyObject_DEL(_PyUnicode_WSTR(unicode));
946 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100947 if (!PyUnicode_IS_ASCII(unicode))
948 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100949 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200950#ifdef Py_DEBUG
951 unicode_fill_invalid(unicode, old_length);
952#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
954 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200955 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200956 return unicode;
957}
958
Alexander Belopolsky40018472011-02-26 01:02:56 +0000959static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200960resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000961{
Victor Stinner95663112011-10-04 01:03:50 +0200962 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100963 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200964 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000966
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967 if (PyUnicode_IS_READY(unicode)) {
968 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200969 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200970 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200971#ifdef Py_DEBUG
972 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
973#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200974
975 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200976 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200977 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
978 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979
980 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
981 PyErr_NoMemory();
982 return -1;
983 }
984 new_size = (length + 1) * char_size;
985
Victor Stinner7a9105a2011-12-12 00:13:42 +0100986 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
987 {
988 PyObject_DEL(_PyUnicode_UTF8(unicode));
989 _PyUnicode_UTF8(unicode) = NULL;
990 _PyUnicode_UTF8_LENGTH(unicode) = 0;
991 }
992
Victor Stinnerfe226c02011-10-03 03:52:20 +0200993 data = (PyObject *)PyObject_REALLOC(data, new_size);
994 if (data == NULL) {
995 PyErr_NoMemory();
996 return -1;
997 }
998 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200999 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001000 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001001 _PyUnicode_WSTR_LENGTH(unicode) = length;
1002 }
1003 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001004 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001005 _PyUnicode_UTF8_LENGTH(unicode) = length;
1006 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001007 _PyUnicode_LENGTH(unicode) = length;
1008 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001009#ifdef Py_DEBUG
1010 unicode_fill_invalid(unicode, old_length);
1011#endif
Victor Stinner95663112011-10-04 01:03:50 +02001012 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001013 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001014 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001015 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001016 }
Victor Stinner95663112011-10-04 01:03:50 +02001017 assert(_PyUnicode_WSTR(unicode) != NULL);
1018
1019 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001020 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001021 PyErr_NoMemory();
1022 return -1;
1023 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001024 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001025 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001026 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001027 if (!wstr) {
1028 PyErr_NoMemory();
1029 return -1;
1030 }
1031 _PyUnicode_WSTR(unicode) = wstr;
1032 _PyUnicode_WSTR(unicode)[length] = 0;
1033 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001034 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001035 return 0;
1036}
1037
Victor Stinnerfe226c02011-10-03 03:52:20 +02001038static PyObject*
1039resize_copy(PyObject *unicode, Py_ssize_t length)
1040{
1041 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001042 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001043 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001045 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046
1047 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1048 if (copy == NULL)
1049 return NULL;
1050
1051 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001052 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001054 }
1055 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001056 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001057
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001058 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001059 if (w == NULL)
1060 return NULL;
1061 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1062 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001063 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001064 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001065 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001066 }
1067}
1068
Guido van Rossumd57fd912000-03-10 22:53:23 +00001069/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001070 Ux0000 terminated; some code (e.g. new_identifier)
1071 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072
1073 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001074 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075
1076*/
1077
Alexander Belopolsky40018472011-02-26 01:02:56 +00001078static PyUnicodeObject *
1079_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001080{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001081 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001083
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 if (length == 0 && unicode_empty != NULL) {
1086 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001087 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001088 }
1089
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001090 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001091 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001092 return (PyUnicodeObject *)PyErr_NoMemory();
1093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001094 if (length < 0) {
1095 PyErr_SetString(PyExc_SystemError,
1096 "Negative size passed to _PyUnicode_New");
1097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001098 }
1099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1101 if (unicode == NULL)
1102 return NULL;
1103 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001104
1105 _PyUnicode_WSTR_LENGTH(unicode) = length;
1106 _PyUnicode_HASH(unicode) = -1;
1107 _PyUnicode_STATE(unicode).interned = 0;
1108 _PyUnicode_STATE(unicode).kind = 0;
1109 _PyUnicode_STATE(unicode).compact = 0;
1110 _PyUnicode_STATE(unicode).ready = 0;
1111 _PyUnicode_STATE(unicode).ascii = 0;
1112 _PyUnicode_DATA_ANY(unicode) = NULL;
1113 _PyUnicode_LENGTH(unicode) = 0;
1114 _PyUnicode_UTF8(unicode) = NULL;
1115 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1118 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001119 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001120 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001121 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123
Jeremy Hyltond8082792003-09-16 19:41:39 +00001124 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001125 * the caller fails before initializing str -- unicode_resize()
1126 * reads str[0], and the Keep-Alive optimization can keep memory
1127 * allocated for str alive across a call to unicode_dealloc(unicode).
1128 * We don't want unicode_resize to read uninitialized memory in
1129 * that case.
1130 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131 _PyUnicode_WSTR(unicode)[0] = 0;
1132 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001133
Victor Stinner7931d9a2011-11-04 00:22:48 +01001134 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001135 return unicode;
1136}
1137
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138static const char*
1139unicode_kind_name(PyObject *unicode)
1140{
Victor Stinner42dfd712011-10-03 14:41:45 +02001141 /* don't check consistency: unicode_kind_name() is called from
1142 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001143 if (!PyUnicode_IS_COMPACT(unicode))
1144 {
1145 if (!PyUnicode_IS_READY(unicode))
1146 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001147 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001148 {
1149 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001150 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 return "legacy ascii";
1152 else
1153 return "legacy latin1";
1154 case PyUnicode_2BYTE_KIND:
1155 return "legacy UCS2";
1156 case PyUnicode_4BYTE_KIND:
1157 return "legacy UCS4";
1158 default:
1159 return "<legacy invalid kind>";
1160 }
1161 }
1162 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001163 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001164 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001165 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001166 return "ascii";
1167 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001168 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001169 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001170 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001171 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001172 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001173 default:
1174 return "<invalid compact kind>";
1175 }
1176}
1177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001179/* Functions wrapping macros for use in debugger */
1180char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001181 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001182}
1183
1184void *_PyUnicode_compact_data(void *unicode) {
1185 return _PyUnicode_COMPACT_DATA(unicode);
1186}
1187void *_PyUnicode_data(void *unicode){
1188 printf("obj %p\n", unicode);
1189 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1190 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1191 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1192 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1193 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1194 return PyUnicode_DATA(unicode);
1195}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001196
1197void
1198_PyUnicode_Dump(PyObject *op)
1199{
1200 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001201 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1202 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1203 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001206 {
1207 if (ascii->state.ascii)
1208 data = (ascii + 1);
1209 else
1210 data = (compact + 1);
1211 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001212 else
1213 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001214 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1215 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001216
Victor Stinnera849a4b2011-10-03 12:12:11 +02001217 if (ascii->wstr == data)
1218 printf("shared ");
1219 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001220
Victor Stinnera3b334d2011-10-03 13:53:37 +02001221 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001222 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001223 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1224 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001225 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1226 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001227 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001228 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001229}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001230#endif
1231
1232PyObject *
1233PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1234{
1235 PyObject *obj;
1236 PyCompactUnicodeObject *unicode;
1237 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001238 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001239 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001240 Py_ssize_t char_size;
1241 Py_ssize_t struct_size;
1242
1243 /* Optimization for empty strings */
1244 if (size == 0 && unicode_empty != NULL) {
1245 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001246 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 }
1248
Victor Stinner9e9d6892011-10-04 01:02:02 +02001249 is_ascii = 0;
1250 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 struct_size = sizeof(PyCompactUnicodeObject);
1252 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001253 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254 char_size = 1;
1255 is_ascii = 1;
1256 struct_size = sizeof(PyASCIIObject);
1257 }
1258 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001259 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 char_size = 1;
1261 }
1262 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001263 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 char_size = 2;
1265 if (sizeof(wchar_t) == 2)
1266 is_sharing = 1;
1267 }
1268 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001269 if (maxchar > MAX_UNICODE) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "invalid maximum character passed to PyUnicode_New");
1272 return NULL;
1273 }
Victor Stinner8f825062012-04-27 13:55:39 +02001274 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 char_size = 4;
1276 if (sizeof(wchar_t) == 4)
1277 is_sharing = 1;
1278 }
1279
1280 /* Ensure we won't overflow the size. */
1281 if (size < 0) {
1282 PyErr_SetString(PyExc_SystemError,
1283 "Negative size passed to PyUnicode_New");
1284 return NULL;
1285 }
1286 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1287 return PyErr_NoMemory();
1288
1289 /* Duplicated allocation code from _PyObject_New() instead of a call to
1290 * PyObject_New() so we are able to allocate space for the object and
1291 * it's data buffer.
1292 */
1293 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1294 if (obj == NULL)
1295 return PyErr_NoMemory();
1296 obj = PyObject_INIT(obj, &PyUnicode_Type);
1297 if (obj == NULL)
1298 return NULL;
1299
1300 unicode = (PyCompactUnicodeObject *)obj;
1301 if (is_ascii)
1302 data = ((PyASCIIObject*)obj) + 1;
1303 else
1304 data = unicode + 1;
1305 _PyUnicode_LENGTH(unicode) = size;
1306 _PyUnicode_HASH(unicode) = -1;
1307 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001308 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309 _PyUnicode_STATE(unicode).compact = 1;
1310 _PyUnicode_STATE(unicode).ready = 1;
1311 _PyUnicode_STATE(unicode).ascii = is_ascii;
1312 if (is_ascii) {
1313 ((char*)data)[size] = 0;
1314 _PyUnicode_WSTR(unicode) = NULL;
1315 }
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((char*)data)[size] = 0;
1318 _PyUnicode_WSTR(unicode) = NULL;
1319 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001321 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001322 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 else {
1324 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001325 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001326 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001328 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001329 ((Py_UCS4*)data)[size] = 0;
1330 if (is_sharing) {
1331 _PyUnicode_WSTR_LENGTH(unicode) = size;
1332 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1333 }
1334 else {
1335 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1336 _PyUnicode_WSTR(unicode) = NULL;
1337 }
1338 }
Victor Stinner8f825062012-04-27 13:55:39 +02001339#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001340 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001341#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001342 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 return obj;
1344}
1345
1346#if SIZEOF_WCHAR_T == 2
1347/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1348 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001349 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350
1351 This function assumes that unicode can hold one more code point than wstr
1352 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001353static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001355 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356{
1357 const wchar_t *iter;
1358 Py_UCS4 *ucs4_out;
1359
Victor Stinner910337b2011-10-03 03:20:16 +02001360 assert(unicode != NULL);
1361 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1363 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1364
1365 for (iter = begin; iter < end; ) {
1366 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1367 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001368 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1369 && (iter+1) < end
1370 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 {
Victor Stinner551ac952011-11-29 22:58:13 +01001372 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373 iter += 2;
1374 }
1375 else {
1376 *ucs4_out++ = *iter;
1377 iter++;
1378 }
1379 }
1380 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1381 _PyUnicode_GET_LENGTH(unicode)));
1382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383}
1384#endif
1385
Victor Stinnercd9950f2011-10-02 00:34:53 +02001386static int
Victor Stinner488fa492011-12-12 00:01:39 +01001387unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001388{
Victor Stinner488fa492011-12-12 00:01:39 +01001389 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001390 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001391 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001392 return -1;
1393 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001394 return 0;
1395}
1396
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397static int
1398_copy_characters(PyObject *to, Py_ssize_t to_start,
1399 PyObject *from, Py_ssize_t from_start,
1400 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001402 unsigned int from_kind, to_kind;
1403 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404
Victor Stinneree4544c2012-05-09 22:24:08 +02001405 assert(0 <= how_many);
1406 assert(0 <= from_start);
1407 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001408 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001409 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001410 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerd3f08822012-05-29 12:57:52 +02001412 assert(PyUnicode_Check(to));
1413 assert(PyUnicode_IS_READY(to));
1414 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1415
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001416 if (how_many == 0)
1417 return 0;
1418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001420 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001422 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423
Victor Stinnerf1852262012-06-16 16:38:26 +02001424#ifdef Py_DEBUG
1425 if (!check_maxchar
1426 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1427 {
1428 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1429 Py_UCS4 ch;
1430 Py_ssize_t i;
1431 for (i=0; i < how_many; i++) {
1432 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1433 assert(ch <= to_maxchar);
1434 }
1435 }
1436#endif
1437
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001438 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001439 if (check_maxchar
1440 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1441 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001442 /* Writing Latin-1 characters into an ASCII string requires to
1443 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001444 Py_UCS4 max_char;
1445 max_char = ucs1lib_find_max_char(from_data,
1446 (Py_UCS1*)from_data + how_many);
1447 if (max_char >= 128)
1448 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001449 }
Christian Heimesf051e432016-09-13 20:22:02 +02001450 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001451 (char*)from_data + from_kind * from_start,
1452 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001454 else if (from_kind == PyUnicode_1BYTE_KIND
1455 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001456 {
1457 _PyUnicode_CONVERT_BYTES(
1458 Py_UCS1, Py_UCS2,
1459 PyUnicode_1BYTE_DATA(from) + from_start,
1460 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1461 PyUnicode_2BYTE_DATA(to) + to_start
1462 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001463 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001464 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001465 && to_kind == PyUnicode_4BYTE_KIND)
1466 {
1467 _PyUnicode_CONVERT_BYTES(
1468 Py_UCS1, Py_UCS4,
1469 PyUnicode_1BYTE_DATA(from) + from_start,
1470 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1471 PyUnicode_4BYTE_DATA(to) + to_start
1472 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001473 }
1474 else if (from_kind == PyUnicode_2BYTE_KIND
1475 && to_kind == PyUnicode_4BYTE_KIND)
1476 {
1477 _PyUnicode_CONVERT_BYTES(
1478 Py_UCS2, Py_UCS4,
1479 PyUnicode_2BYTE_DATA(from) + from_start,
1480 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1481 PyUnicode_4BYTE_DATA(to) + to_start
1482 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001483 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001484 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001485 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1486
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001487 if (!check_maxchar) {
1488 if (from_kind == PyUnicode_2BYTE_KIND
1489 && to_kind == PyUnicode_1BYTE_KIND)
1490 {
1491 _PyUnicode_CONVERT_BYTES(
1492 Py_UCS2, Py_UCS1,
1493 PyUnicode_2BYTE_DATA(from) + from_start,
1494 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1495 PyUnicode_1BYTE_DATA(to) + to_start
1496 );
1497 }
1498 else if (from_kind == PyUnicode_4BYTE_KIND
1499 && to_kind == PyUnicode_1BYTE_KIND)
1500 {
1501 _PyUnicode_CONVERT_BYTES(
1502 Py_UCS4, Py_UCS1,
1503 PyUnicode_4BYTE_DATA(from) + from_start,
1504 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1505 PyUnicode_1BYTE_DATA(to) + to_start
1506 );
1507 }
1508 else if (from_kind == PyUnicode_4BYTE_KIND
1509 && to_kind == PyUnicode_2BYTE_KIND)
1510 {
1511 _PyUnicode_CONVERT_BYTES(
1512 Py_UCS4, Py_UCS2,
1513 PyUnicode_4BYTE_DATA(from) + from_start,
1514 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1515 PyUnicode_2BYTE_DATA(to) + to_start
1516 );
1517 }
1518 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001519 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001520 }
1521 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001522 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001523 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001524 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001525 Py_ssize_t i;
1526
Victor Stinnera0702ab2011-09-29 14:14:38 +02001527 for (i=0; i < how_many; i++) {
1528 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001529 if (ch > to_maxchar)
1530 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001531 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1532 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001533 }
1534 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001535 return 0;
1536}
1537
Victor Stinnerd3f08822012-05-29 12:57:52 +02001538void
1539_PyUnicode_FastCopyCharacters(
1540 PyObject *to, Py_ssize_t to_start,
1541 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001542{
1543 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1544}
1545
1546Py_ssize_t
1547PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1548 PyObject *from, Py_ssize_t from_start,
1549 Py_ssize_t how_many)
1550{
1551 int err;
1552
1553 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1554 PyErr_BadInternalCall();
1555 return -1;
1556 }
1557
Benjamin Petersonbac79492012-01-14 13:34:47 -05001558 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001559 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001560 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001561 return -1;
1562
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001563 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001564 PyErr_SetString(PyExc_IndexError, "string index out of range");
1565 return -1;
1566 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001567 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001568 PyErr_SetString(PyExc_IndexError, "string index out of range");
1569 return -1;
1570 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001571 if (how_many < 0) {
1572 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1573 return -1;
1574 }
1575 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1577 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001578 "Cannot write %zi characters at %zi "
1579 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001580 how_many, to_start, PyUnicode_GET_LENGTH(to));
1581 return -1;
1582 }
1583
1584 if (how_many == 0)
1585 return 0;
1586
Victor Stinner488fa492011-12-12 00:01:39 +01001587 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001588 return -1;
1589
1590 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1591 if (err) {
1592 PyErr_Format(PyExc_SystemError,
1593 "Cannot copy %s characters "
1594 "into a string of %s characters",
1595 unicode_kind_name(from),
1596 unicode_kind_name(to));
1597 return -1;
1598 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001599 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600}
1601
Victor Stinner17222162011-09-28 22:15:37 +02001602/* Find the maximum code point and count the number of surrogate pairs so a
1603 correct string length can be computed before converting a string to UCS4.
1604 This function counts single surrogates as a character and not as a pair.
1605
1606 Return 0 on success, or -1 on error. */
1607static int
1608find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1609 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610{
1611 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001612 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001613
Victor Stinnerc53be962011-10-02 21:33:54 +02001614 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 *num_surrogates = 0;
1616 *maxchar = 0;
1617
1618 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001619#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001620 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1621 && (iter+1) < end
1622 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1623 {
1624 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1625 ++(*num_surrogates);
1626 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 }
1628 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001629#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001630 {
1631 ch = *iter;
1632 iter++;
1633 }
1634 if (ch > *maxchar) {
1635 *maxchar = ch;
1636 if (*maxchar > MAX_UNICODE) {
1637 PyErr_Format(PyExc_ValueError,
1638 "character U+%x is not in range [U+0000; U+10ffff]",
1639 ch);
1640 return -1;
1641 }
1642 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643 }
1644 return 0;
1645}
1646
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001647int
1648_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649{
1650 wchar_t *end;
1651 Py_UCS4 maxchar = 0;
1652 Py_ssize_t num_surrogates;
1653#if SIZEOF_WCHAR_T == 2
1654 Py_ssize_t length_wo_surrogates;
1655#endif
1656
Georg Brandl7597add2011-10-05 16:36:47 +02001657 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001658 strings were created using _PyObject_New() and where no canonical
1659 representation (the str field) has been set yet aka strings
1660 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001661 assert(_PyUnicode_CHECK(unicode));
1662 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001663 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001664 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001665 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001666 /* Actually, it should neither be interned nor be anything else: */
1667 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001670 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001671 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001673
1674 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001675 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1676 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001677 PyErr_NoMemory();
1678 return -1;
1679 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001680 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001681 _PyUnicode_WSTR(unicode), end,
1682 PyUnicode_1BYTE_DATA(unicode));
1683 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1684 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1685 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1686 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001687 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001688 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001689 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 }
1691 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001692 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001693 _PyUnicode_UTF8(unicode) = NULL;
1694 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001695 }
1696 PyObject_FREE(_PyUnicode_WSTR(unicode));
1697 _PyUnicode_WSTR(unicode) = NULL;
1698 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1699 }
1700 /* In this case we might have to convert down from 4-byte native
1701 wchar_t to 2-byte unicode. */
1702 else if (maxchar < 65536) {
1703 assert(num_surrogates == 0 &&
1704 "FindMaxCharAndNumSurrogatePairs() messed up");
1705
Victor Stinner506f5922011-09-28 22:34:18 +02001706#if SIZEOF_WCHAR_T == 2
1707 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001708 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001709 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1710 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1711 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001712 _PyUnicode_UTF8(unicode) = NULL;
1713 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001714#else
1715 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001716 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001717 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001718 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001719 PyErr_NoMemory();
1720 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 }
Victor Stinner506f5922011-09-28 22:34:18 +02001722 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1723 _PyUnicode_WSTR(unicode), end,
1724 PyUnicode_2BYTE_DATA(unicode));
1725 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1726 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1727 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001728 _PyUnicode_UTF8(unicode) = NULL;
1729 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001730 PyObject_FREE(_PyUnicode_WSTR(unicode));
1731 _PyUnicode_WSTR(unicode) = NULL;
1732 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1733#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 }
1735 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1736 else {
1737#if SIZEOF_WCHAR_T == 2
1738 /* in case the native representation is 2-bytes, we need to allocate a
1739 new normalized 4-byte version. */
1740 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001741 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1742 PyErr_NoMemory();
1743 return -1;
1744 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001745 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1746 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 PyErr_NoMemory();
1748 return -1;
1749 }
1750 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1751 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001752 _PyUnicode_UTF8(unicode) = NULL;
1753 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001754 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1755 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001756 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 PyObject_FREE(_PyUnicode_WSTR(unicode));
1758 _PyUnicode_WSTR(unicode) = NULL;
1759 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1760#else
1761 assert(num_surrogates == 0);
1762
Victor Stinnerc3c74152011-10-02 20:39:55 +02001763 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001765 _PyUnicode_UTF8(unicode) = NULL;
1766 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1768#endif
1769 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1770 }
1771 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001772 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 return 0;
1774}
1775
Alexander Belopolsky40018472011-02-26 01:02:56 +00001776static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001777unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001778{
Walter Dörwald16807132007-05-25 13:52:07 +00001779 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001780 case SSTATE_NOT_INTERNED:
1781 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001782
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 case SSTATE_INTERNED_MORTAL:
1784 /* revive dead object temporarily for DelItem */
1785 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001786 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001787 Py_FatalError(
1788 "deletion of interned string failed");
1789 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001790
Benjamin Peterson29060642009-01-31 22:14:21 +00001791 case SSTATE_INTERNED_IMMORTAL:
1792 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001793 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001794
Benjamin Peterson29060642009-01-31 22:14:21 +00001795 default:
1796 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001797 }
1798
Victor Stinner03490912011-10-03 23:45:12 +02001799 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001801 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001802 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001803 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1804 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001806 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807}
1808
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001809#ifdef Py_DEBUG
1810static int
1811unicode_is_singleton(PyObject *unicode)
1812{
1813 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1814 if (unicode == unicode_empty)
1815 return 1;
1816 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1817 {
1818 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1819 if (ch < 256 && unicode_latin1[ch] == unicode)
1820 return 1;
1821 }
1822 return 0;
1823}
1824#endif
1825
Alexander Belopolsky40018472011-02-26 01:02:56 +00001826static int
Victor Stinner488fa492011-12-12 00:01:39 +01001827unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001828{
Victor Stinner488fa492011-12-12 00:01:39 +01001829 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001830 if (Py_REFCNT(unicode) != 1)
1831 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001832 if (_PyUnicode_HASH(unicode) != -1)
1833 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001834 if (PyUnicode_CHECK_INTERNED(unicode))
1835 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001836 if (!PyUnicode_CheckExact(unicode))
1837 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001838#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001839 /* singleton refcount is greater than 1 */
1840 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001841#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001842 return 1;
1843}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001844
Victor Stinnerfe226c02011-10-03 03:52:20 +02001845static int
1846unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1847{
1848 PyObject *unicode;
1849 Py_ssize_t old_length;
1850
1851 assert(p_unicode != NULL);
1852 unicode = *p_unicode;
1853
1854 assert(unicode != NULL);
1855 assert(PyUnicode_Check(unicode));
1856 assert(0 <= length);
1857
Victor Stinner910337b2011-10-03 03:20:16 +02001858 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001859 old_length = PyUnicode_WSTR_LENGTH(unicode);
1860 else
1861 old_length = PyUnicode_GET_LENGTH(unicode);
1862 if (old_length == length)
1863 return 0;
1864
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001865 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001866 _Py_INCREF_UNICODE_EMPTY();
1867 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001868 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001869 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001870 return 0;
1871 }
1872
Victor Stinner488fa492011-12-12 00:01:39 +01001873 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874 PyObject *copy = resize_copy(unicode, length);
1875 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001876 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001877 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001878 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001879 }
1880
Victor Stinnerfe226c02011-10-03 03:52:20 +02001881 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001882 PyObject *new_unicode = resize_compact(unicode, length);
1883 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001884 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001885 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001886 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001887 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001888 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001889}
1890
Alexander Belopolsky40018472011-02-26 01:02:56 +00001891int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001892PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001893{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001894 PyObject *unicode;
1895 if (p_unicode == NULL) {
1896 PyErr_BadInternalCall();
1897 return -1;
1898 }
1899 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001900 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001901 {
1902 PyErr_BadInternalCall();
1903 return -1;
1904 }
1905 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001906}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001907
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001908/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001909
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001910 WARNING: The function doesn't copy the terminating null character and
1911 doesn't check the maximum character (may write a latin1 character in an
1912 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001913static void
1914unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1915 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001916{
1917 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1918 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001919 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001920
1921 switch (kind) {
1922 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001923 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001924#ifdef Py_DEBUG
1925 if (PyUnicode_IS_ASCII(unicode)) {
1926 Py_UCS4 maxchar = ucs1lib_find_max_char(
1927 (const Py_UCS1*)str,
1928 (const Py_UCS1*)str + len);
1929 assert(maxchar < 128);
1930 }
1931#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001932 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001933 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001934 }
1935 case PyUnicode_2BYTE_KIND: {
1936 Py_UCS2 *start = (Py_UCS2 *)data + index;
1937 Py_UCS2 *ucs2 = start;
1938 assert(index <= PyUnicode_GET_LENGTH(unicode));
1939
Victor Stinner184252a2012-06-16 02:57:41 +02001940 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941 *ucs2 = (Py_UCS2)*str;
1942
1943 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001944 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001945 }
1946 default: {
1947 Py_UCS4 *start = (Py_UCS4 *)data + index;
1948 Py_UCS4 *ucs4 = start;
1949 assert(kind == PyUnicode_4BYTE_KIND);
1950 assert(index <= PyUnicode_GET_LENGTH(unicode));
1951
Victor Stinner184252a2012-06-16 02:57:41 +02001952 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001953 *ucs4 = (Py_UCS4)*str;
1954
1955 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001956 }
1957 }
1958}
1959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960static PyObject*
1961get_latin1_char(unsigned char ch)
1962{
Victor Stinnera464fc12011-10-02 20:39:30 +02001963 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001964 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001965 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001966 if (!unicode)
1967 return NULL;
1968 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001969 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001970 unicode_latin1[ch] = unicode;
1971 }
1972 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001973 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974}
1975
Victor Stinner985a82a2014-01-03 12:53:47 +01001976static PyObject*
1977unicode_char(Py_UCS4 ch)
1978{
1979 PyObject *unicode;
1980
1981 assert(ch <= MAX_UNICODE);
1982
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001983 if (ch < 256)
1984 return get_latin1_char(ch);
1985
Victor Stinner985a82a2014-01-03 12:53:47 +01001986 unicode = PyUnicode_New(1, ch);
1987 if (unicode == NULL)
1988 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001989
1990 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1991 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001992 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001993 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001994 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1995 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1996 }
1997 assert(_PyUnicode_CheckConsistency(unicode, 1));
1998 return unicode;
1999}
2000
Alexander Belopolsky40018472011-02-26 01:02:56 +00002001PyObject *
2002PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002003{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002004 if (u == NULL)
2005 return (PyObject*)_PyUnicode_New(size);
2006
2007 if (size < 0) {
2008 PyErr_BadInternalCall();
2009 return NULL;
2010 }
2011
2012 return PyUnicode_FromWideChar(u, size);
2013}
2014
2015PyObject *
2016PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2017{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002018 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 Py_UCS4 maxchar = 0;
2020 Py_ssize_t num_surrogates;
2021
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002022 if (u == NULL && size != 0) {
2023 PyErr_BadInternalCall();
2024 return NULL;
2025 }
2026
2027 if (size == -1) {
2028 size = wcslen(u);
2029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002030
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002031 /* If the Unicode data is known at construction time, we can apply
2032 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002035 if (size == 0)
2036 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038 /* Single character Unicode objects in the Latin-1 range are
2039 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002040 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 return get_latin1_char((unsigned char)*u);
2042
2043 /* If not empty and not single character, copy the Unicode data
2044 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002045 if (find_maxchar_surrogates(u, u + size,
2046 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return NULL;
2048
Victor Stinner8faf8212011-12-08 22:14:11 +01002049 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050 if (!unicode)
2051 return NULL;
2052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053 switch (PyUnicode_KIND(unicode)) {
2054 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002055 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2057 break;
2058 case PyUnicode_2BYTE_KIND:
2059#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002060 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002062 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2064#endif
2065 break;
2066 case PyUnicode_4BYTE_KIND:
2067#if SIZEOF_WCHAR_T == 2
2068 /* This is the only case which has to process surrogates, thus
2069 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002070 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071#else
2072 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002073 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074#endif
2075 break;
2076 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002077 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002079
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002080 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081}
2082
Alexander Belopolsky40018472011-02-26 01:02:56 +00002083PyObject *
2084PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002085{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002086 if (size < 0) {
2087 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002088 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002089 return NULL;
2090 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002091 if (u != NULL)
2092 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2093 else
2094 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002095}
2096
Alexander Belopolsky40018472011-02-26 01:02:56 +00002097PyObject *
2098PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002099{
2100 size_t size = strlen(u);
2101 if (size > PY_SSIZE_T_MAX) {
2102 PyErr_SetString(PyExc_OverflowError, "input too long");
2103 return NULL;
2104 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002105 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002106}
2107
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002108PyObject *
2109_PyUnicode_FromId(_Py_Identifier *id)
2110{
2111 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002112 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2113 strlen(id->string),
2114 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002115 if (!id->object)
2116 return NULL;
2117 PyUnicode_InternInPlace(&id->object);
2118 assert(!id->next);
2119 id->next = static_strings;
2120 static_strings = id;
2121 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002122 return id->object;
2123}
2124
2125void
2126_PyUnicode_ClearStaticStrings()
2127{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002128 _Py_Identifier *tmp, *s = static_strings;
2129 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002130 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002131 tmp = s->next;
2132 s->next = NULL;
2133 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002134 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002135 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002136}
2137
Benjamin Peterson0df54292012-03-26 14:50:32 -04002138/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002139
Victor Stinnerd3f08822012-05-29 12:57:52 +02002140PyObject*
2141_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002142{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002143 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002144 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002145 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002146#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002147 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002148#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002149 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002150 }
Victor Stinner785938e2011-12-11 20:09:03 +01002151 unicode = PyUnicode_New(size, 127);
2152 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002153 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002154 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2155 assert(_PyUnicode_CheckConsistency(unicode, 1));
2156 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002157}
2158
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002159static Py_UCS4
2160kind_maxchar_limit(unsigned int kind)
2161{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002162 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002163 case PyUnicode_1BYTE_KIND:
2164 return 0x80;
2165 case PyUnicode_2BYTE_KIND:
2166 return 0x100;
2167 case PyUnicode_4BYTE_KIND:
2168 return 0x10000;
2169 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002170 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002171 }
2172}
2173
Victor Stinner702c7342011-10-05 13:50:52 +02002174static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002175_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002178 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002179
Serhiy Storchaka678db842013-01-26 12:16:36 +02002180 if (size == 0)
2181 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002182 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002183 if (size == 1)
2184 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002185
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002186 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002187 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002188 if (!res)
2189 return NULL;
2190 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002191 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002193}
2194
Victor Stinnere57b1c02011-09-28 22:20:48 +02002195static PyObject*
2196_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197{
2198 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002199 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002200
Serhiy Storchaka678db842013-01-26 12:16:36 +02002201 if (size == 0)
2202 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002203 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002204 if (size == 1)
2205 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002207 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002208 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 if (!res)
2210 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002211 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002213 else {
2214 _PyUnicode_CONVERT_BYTES(
2215 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2216 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002217 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return res;
2219}
2220
Victor Stinnere57b1c02011-09-28 22:20:48 +02002221static PyObject*
2222_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223{
2224 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002225 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002226
Serhiy Storchaka678db842013-01-26 12:16:36 +02002227 if (size == 0)
2228 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002229 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002230 if (size == 1)
2231 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002232
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002233 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002234 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002235 if (!res)
2236 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002237 if (max_char < 256)
2238 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2239 PyUnicode_1BYTE_DATA(res));
2240 else if (max_char < 0x10000)
2241 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2242 PyUnicode_2BYTE_DATA(res));
2243 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002244 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002245 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 return res;
2247}
2248
2249PyObject*
2250PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2251{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002252 if (size < 0) {
2253 PyErr_SetString(PyExc_ValueError, "size must be positive");
2254 return NULL;
2255 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002256 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002258 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002260 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002262 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002263 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002264 PyErr_SetString(PyExc_SystemError, "invalid kind");
2265 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267}
2268
Victor Stinnerece58de2012-04-23 23:36:38 +02002269Py_UCS4
2270_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2271{
2272 enum PyUnicode_Kind kind;
2273 void *startptr, *endptr;
2274
2275 assert(PyUnicode_IS_READY(unicode));
2276 assert(0 <= start);
2277 assert(end <= PyUnicode_GET_LENGTH(unicode));
2278 assert(start <= end);
2279
2280 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2281 return PyUnicode_MAX_CHAR_VALUE(unicode);
2282
2283 if (start == end)
2284 return 127;
2285
Victor Stinner94d558b2012-04-27 22:26:58 +02002286 if (PyUnicode_IS_ASCII(unicode))
2287 return 127;
2288
Victor Stinnerece58de2012-04-23 23:36:38 +02002289 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002290 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002291 endptr = (char *)startptr + end * kind;
2292 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002293 switch(kind) {
2294 case PyUnicode_1BYTE_KIND:
2295 return ucs1lib_find_max_char(startptr, endptr);
2296 case PyUnicode_2BYTE_KIND:
2297 return ucs2lib_find_max_char(startptr, endptr);
2298 case PyUnicode_4BYTE_KIND:
2299 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002300 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002301 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002302 }
2303}
2304
Victor Stinner25a4b292011-10-06 12:31:55 +02002305/* Ensure that a string uses the most efficient storage, if it is not the
2306 case: create a new string with of the right kind. Write NULL into *p_unicode
2307 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002308static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002309unicode_adjust_maxchar(PyObject **p_unicode)
2310{
2311 PyObject *unicode, *copy;
2312 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002313 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002314 unsigned int kind;
2315
2316 assert(p_unicode != NULL);
2317 unicode = *p_unicode;
2318 assert(PyUnicode_IS_READY(unicode));
2319 if (PyUnicode_IS_ASCII(unicode))
2320 return;
2321
2322 len = PyUnicode_GET_LENGTH(unicode);
2323 kind = PyUnicode_KIND(unicode);
2324 if (kind == PyUnicode_1BYTE_KIND) {
2325 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002326 max_char = ucs1lib_find_max_char(u, u + len);
2327 if (max_char >= 128)
2328 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002329 }
2330 else if (kind == PyUnicode_2BYTE_KIND) {
2331 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002332 max_char = ucs2lib_find_max_char(u, u + len);
2333 if (max_char >= 256)
2334 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002335 }
2336 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002337 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002338 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002339 max_char = ucs4lib_find_max_char(u, u + len);
2340 if (max_char >= 0x10000)
2341 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002342 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002343 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002344 if (copy != NULL)
2345 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002346 Py_DECREF(unicode);
2347 *p_unicode = copy;
2348}
2349
Victor Stinner034f6cf2011-09-30 02:26:44 +02002350PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002351_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002352{
Victor Stinner87af4f22011-11-21 23:03:47 +01002353 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002354 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002355
Victor Stinner034f6cf2011-09-30 02:26:44 +02002356 if (!PyUnicode_Check(unicode)) {
2357 PyErr_BadInternalCall();
2358 return NULL;
2359 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002360 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002361 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002362
Victor Stinner87af4f22011-11-21 23:03:47 +01002363 length = PyUnicode_GET_LENGTH(unicode);
2364 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002365 if (!copy)
2366 return NULL;
2367 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2368
Christian Heimesf051e432016-09-13 20:22:02 +02002369 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002370 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002371 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002372 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002373}
2374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375
Victor Stinnerbc603d12011-10-02 01:00:40 +02002376/* Widen Unicode objects to larger buffers. Don't write terminating null
2377 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002378
2379void*
2380_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2381{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002382 Py_ssize_t len;
2383 void *result;
2384 unsigned int skind;
2385
Benjamin Petersonbac79492012-01-14 13:34:47 -05002386 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002387 return NULL;
2388
2389 len = PyUnicode_GET_LENGTH(s);
2390 skind = PyUnicode_KIND(s);
2391 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002392 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 return NULL;
2394 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002395 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002396 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002397 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002398 if (!result)
2399 return PyErr_NoMemory();
2400 assert(skind == PyUnicode_1BYTE_KIND);
2401 _PyUnicode_CONVERT_BYTES(
2402 Py_UCS1, Py_UCS2,
2403 PyUnicode_1BYTE_DATA(s),
2404 PyUnicode_1BYTE_DATA(s) + len,
2405 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002407 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002408 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 if (!result)
2410 return PyErr_NoMemory();
2411 if (skind == PyUnicode_2BYTE_KIND) {
2412 _PyUnicode_CONVERT_BYTES(
2413 Py_UCS2, Py_UCS4,
2414 PyUnicode_2BYTE_DATA(s),
2415 PyUnicode_2BYTE_DATA(s) + len,
2416 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002418 else {
2419 assert(skind == PyUnicode_1BYTE_KIND);
2420 _PyUnicode_CONVERT_BYTES(
2421 Py_UCS1, Py_UCS4,
2422 PyUnicode_1BYTE_DATA(s),
2423 PyUnicode_1BYTE_DATA(s) + len,
2424 result);
2425 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002427 default:
2428 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 }
Victor Stinner01698042011-10-04 00:04:26 +02002430 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 return NULL;
2432}
2433
2434static Py_UCS4*
2435as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2436 int copy_null)
2437{
2438 int kind;
2439 void *data;
2440 Py_ssize_t len, targetlen;
2441 if (PyUnicode_READY(string) == -1)
2442 return NULL;
2443 kind = PyUnicode_KIND(string);
2444 data = PyUnicode_DATA(string);
2445 len = PyUnicode_GET_LENGTH(string);
2446 targetlen = len;
2447 if (copy_null)
2448 targetlen++;
2449 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002450 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 if (!target) {
2452 PyErr_NoMemory();
2453 return NULL;
2454 }
2455 }
2456 else {
2457 if (targetsize < targetlen) {
2458 PyErr_Format(PyExc_SystemError,
2459 "string is longer than the buffer");
2460 if (copy_null && 0 < targetsize)
2461 target[0] = 0;
2462 return NULL;
2463 }
2464 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002465 if (kind == PyUnicode_1BYTE_KIND) {
2466 Py_UCS1 *start = (Py_UCS1 *) data;
2467 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002469 else if (kind == PyUnicode_2BYTE_KIND) {
2470 Py_UCS2 *start = (Py_UCS2 *) data;
2471 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2472 }
2473 else {
2474 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002475 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 if (copy_null)
2478 target[len] = 0;
2479 return target;
2480}
2481
2482Py_UCS4*
2483PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2484 int copy_null)
2485{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002486 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 PyErr_BadInternalCall();
2488 return NULL;
2489 }
2490 return as_ucs4(string, target, targetsize, copy_null);
2491}
2492
2493Py_UCS4*
2494PyUnicode_AsUCS4Copy(PyObject *string)
2495{
2496 return as_ucs4(string, NULL, 0, 1);
2497}
2498
Victor Stinner15a11362012-10-06 23:48:20 +02002499/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002500 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2501 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2502#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002503
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002504static int
2505unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2506 Py_ssize_t width, Py_ssize_t precision)
2507{
2508 Py_ssize_t length, fill, arglen;
2509 Py_UCS4 maxchar;
2510
2511 if (PyUnicode_READY(str) == -1)
2512 return -1;
2513
2514 length = PyUnicode_GET_LENGTH(str);
2515 if ((precision == -1 || precision >= length)
2516 && width <= length)
2517 return _PyUnicodeWriter_WriteStr(writer, str);
2518
2519 if (precision != -1)
2520 length = Py_MIN(precision, length);
2521
2522 arglen = Py_MAX(length, width);
2523 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2524 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2525 else
2526 maxchar = writer->maxchar;
2527
2528 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2529 return -1;
2530
2531 if (width > length) {
2532 fill = width - length;
2533 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2534 return -1;
2535 writer->pos += fill;
2536 }
2537
2538 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2539 str, 0, length);
2540 writer->pos += length;
2541 return 0;
2542}
2543
2544static int
2545unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2546 Py_ssize_t width, Py_ssize_t precision)
2547{
2548 /* UTF-8 */
2549 Py_ssize_t length;
2550 PyObject *unicode;
2551 int res;
2552
2553 length = strlen(str);
2554 if (precision != -1)
2555 length = Py_MIN(length, precision);
2556 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2557 if (unicode == NULL)
2558 return -1;
2559
2560 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2561 Py_DECREF(unicode);
2562 return res;
2563}
2564
Victor Stinner96865452011-03-01 23:44:09 +00002565static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002566unicode_fromformat_arg(_PyUnicodeWriter *writer,
2567 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002568{
Victor Stinnere215d962012-10-06 23:03:36 +02002569 const char *p;
2570 Py_ssize_t len;
2571 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002572 Py_ssize_t width;
2573 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002574 int longflag;
2575 int longlongflag;
2576 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002577 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002578
2579 p = f;
2580 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002581 zeropad = 0;
2582 if (*f == '0') {
2583 zeropad = 1;
2584 f++;
2585 }
Victor Stinner96865452011-03-01 23:44:09 +00002586
2587 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002588 width = -1;
2589 if (Py_ISDIGIT((unsigned)*f)) {
2590 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002591 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002592 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002593 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002594 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002596 return NULL;
2597 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002599 f++;
2600 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002601 }
2602 precision = -1;
2603 if (*f == '.') {
2604 f++;
2605 if (Py_ISDIGIT((unsigned)*f)) {
2606 precision = (*f - '0');
2607 f++;
2608 while (Py_ISDIGIT((unsigned)*f)) {
2609 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2610 PyErr_SetString(PyExc_ValueError,
2611 "precision too big");
2612 return NULL;
2613 }
2614 precision = (precision * 10) + (*f - '0');
2615 f++;
2616 }
2617 }
Victor Stinner96865452011-03-01 23:44:09 +00002618 if (*f == '%') {
2619 /* "%.3%s" => f points to "3" */
2620 f--;
2621 }
2622 }
2623 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002624 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002625 f--;
2626 }
Victor Stinner96865452011-03-01 23:44:09 +00002627
2628 /* Handle %ld, %lu, %lld and %llu. */
2629 longflag = 0;
2630 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002631 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002632 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002633 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002634 longflag = 1;
2635 ++f;
2636 }
Victor Stinner96865452011-03-01 23:44:09 +00002637 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002638 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002639 longlongflag = 1;
2640 f += 2;
2641 }
Victor Stinner96865452011-03-01 23:44:09 +00002642 }
2643 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002644 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002645 size_tflag = 1;
2646 ++f;
2647 }
Victor Stinnere215d962012-10-06 23:03:36 +02002648
2649 if (f[1] == '\0')
2650 writer->overallocate = 0;
2651
2652 switch (*f) {
2653 case 'c':
2654 {
2655 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002656 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002657 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002658 "character argument not in range(0x110000)");
2659 return NULL;
2660 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002661 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002662 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002663 break;
2664 }
2665
2666 case 'i':
2667 case 'd':
2668 case 'u':
2669 case 'x':
2670 {
2671 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002672 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002673 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002674
2675 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002676 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002677 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002678 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002679 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002680 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002681 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002682 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002683 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002684 va_arg(*vargs, size_t));
2685 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002686 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002687 va_arg(*vargs, unsigned int));
2688 }
2689 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002690 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002691 }
2692 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002693 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002694 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002695 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002696 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002697 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002698 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002699 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002700 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002701 va_arg(*vargs, Py_ssize_t));
2702 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002703 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002704 va_arg(*vargs, int));
2705 }
2706 assert(len >= 0);
2707
Victor Stinnere215d962012-10-06 23:03:36 +02002708 if (precision < len)
2709 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002710
2711 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2713 return NULL;
2714
Victor Stinnere215d962012-10-06 23:03:36 +02002715 if (width > precision) {
2716 Py_UCS4 fillchar;
2717 fill = width - precision;
2718 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002719 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2720 return NULL;
2721 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002722 }
Victor Stinner15a11362012-10-06 23:48:20 +02002723 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002724 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002725 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2726 return NULL;
2727 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002728 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002729
Victor Stinner4a587072013-11-19 12:54:53 +01002730 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2731 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002732 break;
2733 }
2734
2735 case 'p':
2736 {
2737 char number[MAX_LONG_LONG_CHARS];
2738
2739 len = sprintf(number, "%p", va_arg(*vargs, void*));
2740 assert(len >= 0);
2741
2742 /* %p is ill-defined: ensure leading 0x. */
2743 if (number[1] == 'X')
2744 number[1] = 'x';
2745 else if (number[1] != 'x') {
2746 memmove(number + 2, number,
2747 strlen(number) + 1);
2748 number[0] = '0';
2749 number[1] = 'x';
2750 len += 2;
2751 }
2752
Victor Stinner4a587072013-11-19 12:54:53 +01002753 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002754 return NULL;
2755 break;
2756 }
2757
2758 case 's':
2759 {
2760 /* UTF-8 */
2761 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002762 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002763 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002764 break;
2765 }
2766
2767 case 'U':
2768 {
2769 PyObject *obj = va_arg(*vargs, PyObject *);
2770 assert(obj && _PyUnicode_CHECK(obj));
2771
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002772 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002773 return NULL;
2774 break;
2775 }
2776
2777 case 'V':
2778 {
2779 PyObject *obj = va_arg(*vargs, PyObject *);
2780 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002781 if (obj) {
2782 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002783 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002784 return NULL;
2785 }
2786 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002787 assert(str != NULL);
2788 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002789 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002790 }
2791 break;
2792 }
2793
2794 case 'S':
2795 {
2796 PyObject *obj = va_arg(*vargs, PyObject *);
2797 PyObject *str;
2798 assert(obj);
2799 str = PyObject_Str(obj);
2800 if (!str)
2801 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002802 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002803 Py_DECREF(str);
2804 return NULL;
2805 }
2806 Py_DECREF(str);
2807 break;
2808 }
2809
2810 case 'R':
2811 {
2812 PyObject *obj = va_arg(*vargs, PyObject *);
2813 PyObject *repr;
2814 assert(obj);
2815 repr = PyObject_Repr(obj);
2816 if (!repr)
2817 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002818 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002819 Py_DECREF(repr);
2820 return NULL;
2821 }
2822 Py_DECREF(repr);
2823 break;
2824 }
2825
2826 case 'A':
2827 {
2828 PyObject *obj = va_arg(*vargs, PyObject *);
2829 PyObject *ascii;
2830 assert(obj);
2831 ascii = PyObject_ASCII(obj);
2832 if (!ascii)
2833 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002834 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002835 Py_DECREF(ascii);
2836 return NULL;
2837 }
2838 Py_DECREF(ascii);
2839 break;
2840 }
2841
2842 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002843 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002844 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002845 break;
2846
2847 default:
2848 /* if we stumble upon an unknown formatting code, copy the rest
2849 of the format string to the output string. (we cannot just
2850 skip the code, since there's no way to know what's in the
2851 argument list) */
2852 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002853 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002854 return NULL;
2855 f = p+len;
2856 return f;
2857 }
2858
2859 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002860 return f;
2861}
2862
Walter Dörwaldd2034312007-05-18 16:29:38 +00002863PyObject *
2864PyUnicode_FromFormatV(const char *format, va_list vargs)
2865{
Victor Stinnere215d962012-10-06 23:03:36 +02002866 va_list vargs2;
2867 const char *f;
2868 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002869
Victor Stinner8f674cc2013-04-17 23:02:17 +02002870 _PyUnicodeWriter_Init(&writer);
2871 writer.min_length = strlen(format) + 100;
2872 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002873
Benjamin Peterson0c212142016-09-20 20:39:33 -07002874 // Copy varags to be able to pass a reference to a subfunction.
2875 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002876
2877 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002878 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002879 f = unicode_fromformat_arg(&writer, f, &vargs2);
2880 if (f == NULL)
2881 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002883 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002884 const char *p;
2885 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002886
Victor Stinnere215d962012-10-06 23:03:36 +02002887 p = f;
2888 do
2889 {
2890 if ((unsigned char)*p > 127) {
2891 PyErr_Format(PyExc_ValueError,
2892 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2893 "string, got a non-ASCII byte: 0x%02x",
2894 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002895 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002896 }
2897 p++;
2898 }
2899 while (*p != '\0' && *p != '%');
2900 len = p - f;
2901
2902 if (*p == '\0')
2903 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002904
2905 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002906 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002907
2908 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002909 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002910 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002911 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002912 return _PyUnicodeWriter_Finish(&writer);
2913
2914 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002915 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002916 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918}
2919
Walter Dörwaldd2034312007-05-18 16:29:38 +00002920PyObject *
2921PyUnicode_FromFormat(const char *format, ...)
2922{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002923 PyObject* ret;
2924 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925
2926#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002927 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002928#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002929 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002930#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002931 ret = PyUnicode_FromFormatV(format, vargs);
2932 va_end(vargs);
2933 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002934}
2935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002936#ifdef HAVE_WCHAR_H
2937
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002938/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00002939
Victor Stinnerd88d9832011-09-06 02:00:05 +02002940 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002941 character) required to convert the unicode object. Ignore size argument.
2942
Victor Stinnerd88d9832011-09-06 02:00:05 +02002943 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002944 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002945 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002946Py_ssize_t
2947PyUnicode_AsWideChar(PyObject *unicode,
2948 wchar_t *w,
2949 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00002950{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002951 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 const wchar_t *wstr;
2953
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002954 if (unicode == NULL) {
2955 PyErr_BadInternalCall();
2956 return -1;
2957 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002958 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (wstr == NULL)
2960 return -1;
2961
Victor Stinner5593d8a2010-10-02 11:11:27 +00002962 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002963 if (size > res)
2964 size = res + 1;
2965 else
2966 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002967 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002968 return res;
2969 }
2970 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002971 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002972}
2973
Victor Stinner137c34c2010-09-29 10:25:54 +00002974wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002975PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002976 Py_ssize_t *size)
2977{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002978 const wchar_t *wstr;
2979 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00002980 Py_ssize_t buflen;
2981
2982 if (unicode == NULL) {
2983 PyErr_BadInternalCall();
2984 return NULL;
2985 }
2986
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002987 wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen);
2988 if (wstr == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002989 return NULL;
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002990 }
2991 if (size == NULL && wcslen(wstr) != (size_t)buflen) {
2992 PyErr_SetString(PyExc_ValueError,
2993 "embedded null character");
2994 return NULL;
2995 }
2996
2997 buffer = PyMem_NEW(wchar_t, buflen + 1);
Victor Stinner137c34c2010-09-29 10:25:54 +00002998 if (buffer == NULL) {
2999 PyErr_NoMemory();
3000 return NULL;
3001 }
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003002 memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00003003 if (size != NULL)
3004 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003005 return buffer;
3006}
3007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003008#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003009
Alexander Belopolsky40018472011-02-26 01:02:56 +00003010PyObject *
3011PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003012{
Victor Stinner8faf8212011-12-08 22:14:11 +01003013 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003014 PyErr_SetString(PyExc_ValueError,
3015 "chr() arg not in range(0x110000)");
3016 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003017 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003018
Victor Stinner985a82a2014-01-03 12:53:47 +01003019 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003020}
3021
Alexander Belopolsky40018472011-02-26 01:02:56 +00003022PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003023PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003024{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003025 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003027 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003028 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003029 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003030 Py_INCREF(obj);
3031 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003032 }
3033 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 /* For a Unicode subtype that's not a Unicode object,
3035 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003036 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003037 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003038 PyErr_Format(PyExc_TypeError,
3039 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003040 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003041 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003042}
3043
Alexander Belopolsky40018472011-02-26 01:02:56 +00003044PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003045PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003046 const char *encoding,
3047 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003048{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003049 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003050 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003051
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 PyErr_BadInternalCall();
3054 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003055 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 /* Decoding bytes objects is the most common case and should be fast */
3058 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003059 if (PyBytes_GET_SIZE(obj) == 0)
3060 _Py_RETURN_UNICODE_EMPTY();
3061 v = PyUnicode_Decode(
3062 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3063 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003064 return v;
3065 }
3066
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003067 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 PyErr_SetString(PyExc_TypeError,
3069 "decoding str is not supported");
3070 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003071 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003072
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003073 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3074 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3075 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003076 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003077 Py_TYPE(obj)->tp_name);
3078 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003079 }
Tim Petersced69f82003-09-16 20:30:58 +00003080
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003081 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003082 PyBuffer_Release(&buffer);
3083 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003084 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003085
Serhiy Storchaka05997252013-01-26 12:14:02 +02003086 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003087 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003088 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089}
3090
Victor Stinnerebe17e02016-10-12 13:57:45 +02003091/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3092 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3093 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003094int
3095_Py_normalize_encoding(const char *encoding,
3096 char *lower,
3097 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003098{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003099 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003100 char *l;
3101 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003102 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003103
Victor Stinner942889a2016-09-05 15:40:10 -07003104 assert(encoding != NULL);
3105
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003106 e = encoding;
3107 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003108 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003109 punct = 0;
3110 while (1) {
3111 char c = *e;
3112 if (c == 0) {
3113 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003114 }
Victor Stinner942889a2016-09-05 15:40:10 -07003115
3116 if (Py_ISALNUM(c) || c == '.') {
3117 if (punct && l != lower) {
3118 if (l == l_end) {
3119 return 0;
3120 }
3121 *l++ = '_';
3122 }
3123 punct = 0;
3124
3125 if (l == l_end) {
3126 return 0;
3127 }
3128 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003129 }
3130 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003131 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003132 }
Victor Stinner942889a2016-09-05 15:40:10 -07003133
3134 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003135 }
3136 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003137 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003138}
3139
Alexander Belopolsky40018472011-02-26 01:02:56 +00003140PyObject *
3141PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003142 Py_ssize_t size,
3143 const char *encoding,
3144 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003145{
3146 PyObject *buffer = NULL, *unicode;
3147 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003148 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3149
3150 if (encoding == NULL) {
3151 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3152 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003153
Fred Drakee4315f52000-05-09 19:53:39 +00003154 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003155 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3156 char *lower = buflower;
3157
3158 /* Fast paths */
3159 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3160 lower += 3;
3161 if (*lower == '_') {
3162 /* Match "utf8" and "utf_8" */
3163 lower++;
3164 }
3165
3166 if (lower[0] == '8' && lower[1] == 0) {
3167 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3168 }
3169 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3170 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3171 }
3172 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3173 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3174 }
3175 }
3176 else {
3177 if (strcmp(lower, "ascii") == 0
3178 || strcmp(lower, "us_ascii") == 0) {
3179 return PyUnicode_DecodeASCII(s, size, errors);
3180 }
Steve Dowercc16be82016-09-08 10:35:16 -07003181 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003182 else if (strcmp(lower, "mbcs") == 0) {
3183 return PyUnicode_DecodeMBCS(s, size, errors);
3184 }
3185 #endif
3186 else if (strcmp(lower, "latin1") == 0
3187 || strcmp(lower, "latin_1") == 0
3188 || strcmp(lower, "iso_8859_1") == 0
3189 || strcmp(lower, "iso8859_1") == 0) {
3190 return PyUnicode_DecodeLatin1(s, size, errors);
3191 }
3192 }
Victor Stinner37296e82010-06-10 13:36:23 +00003193 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003194
3195 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003196 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003197 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003198 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003199 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200 if (buffer == NULL)
3201 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003202 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203 if (unicode == NULL)
3204 goto onError;
3205 if (!PyUnicode_Check(unicode)) {
3206 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003207 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3208 "use codecs.decode() to decode to arbitrary types",
3209 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003210 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003211 Py_DECREF(unicode);
3212 goto onError;
3213 }
3214 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003215 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003216
Benjamin Peterson29060642009-01-31 22:14:21 +00003217 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003218 Py_XDECREF(buffer);
3219 return NULL;
3220}
3221
Alexander Belopolsky40018472011-02-26 01:02:56 +00003222PyObject *
3223PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003224 const char *encoding,
3225 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003226{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003227 if (!PyUnicode_Check(unicode)) {
3228 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003229 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003230 }
3231
Serhiy Storchaka00939072016-10-27 21:05:49 +03003232 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3233 "PyUnicode_AsDecodedObject() is deprecated; "
3234 "use PyCodec_Decode() to decode from str", 1) < 0)
3235 return NULL;
3236
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003237 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003239
3240 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003241 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242}
3243
Alexander Belopolsky40018472011-02-26 01:02:56 +00003244PyObject *
3245PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003246 const char *encoding,
3247 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003248{
3249 PyObject *v;
3250
3251 if (!PyUnicode_Check(unicode)) {
3252 PyErr_BadArgument();
3253 goto onError;
3254 }
3255
Serhiy Storchaka00939072016-10-27 21:05:49 +03003256 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3257 "PyUnicode_AsDecodedUnicode() is deprecated; "
3258 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3259 return NULL;
3260
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003261 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003262 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003263
3264 /* Decode via the codec registry */
3265 v = PyCodec_Decode(unicode, encoding, errors);
3266 if (v == NULL)
3267 goto onError;
3268 if (!PyUnicode_Check(v)) {
3269 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003270 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3271 "use codecs.decode() to decode to arbitrary types",
3272 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003273 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003274 Py_DECREF(v);
3275 goto onError;
3276 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003277 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003278
Benjamin Peterson29060642009-01-31 22:14:21 +00003279 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003280 return NULL;
3281}
3282
Alexander Belopolsky40018472011-02-26 01:02:56 +00003283PyObject *
3284PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003285 Py_ssize_t size,
3286 const char *encoding,
3287 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003288{
3289 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003290
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003291 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003294 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3295 Py_DECREF(unicode);
3296 return v;
3297}
3298
Alexander Belopolsky40018472011-02-26 01:02:56 +00003299PyObject *
3300PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003301 const char *encoding,
3302 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003303{
3304 PyObject *v;
3305
3306 if (!PyUnicode_Check(unicode)) {
3307 PyErr_BadArgument();
3308 goto onError;
3309 }
3310
Serhiy Storchaka00939072016-10-27 21:05:49 +03003311 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3312 "PyUnicode_AsEncodedObject() is deprecated; "
3313 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3314 "or PyCodec_Encode() for generic encoding", 1) < 0)
3315 return NULL;
3316
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003317 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003318 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003319
3320 /* Encode via the codec registry */
3321 v = PyCodec_Encode(unicode, encoding, errors);
3322 if (v == NULL)
3323 goto onError;
3324 return v;
3325
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003327 return NULL;
3328}
3329
Victor Stinner1b579672011-12-17 05:47:23 +01003330static int
3331locale_error_handler(const char *errors, int *surrogateescape)
3332{
Victor Stinner50149202015-09-22 00:26:54 +02003333 _Py_error_handler error_handler = get_error_handler(errors);
3334 switch (error_handler)
3335 {
3336 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003337 *surrogateescape = 0;
3338 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003339 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003340 *surrogateescape = 1;
3341 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003342 default:
3343 PyErr_Format(PyExc_ValueError,
3344 "only 'strict' and 'surrogateescape' error handlers "
3345 "are supported, not '%s'",
3346 errors);
3347 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003348 }
Victor Stinner1b579672011-12-17 05:47:23 +01003349}
3350
Victor Stinner2cba6b82018-01-10 22:46:15 +01003351static PyObject *
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003352unicode_encode_locale(PyObject *unicode, const char *errors,
3353 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003354{
Victor Stinner1b579672011-12-17 05:47:23 +01003355 int surrogateescape;
Victor Stinner1b579672011-12-17 05:47:23 +01003356 if (locale_error_handler(errors, &surrogateescape) < 0)
3357 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003358
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003359 Py_ssize_t wlen;
3360 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3361 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003362 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003363 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003364
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003365 Py_ssize_t wlen2 = wcslen(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003366 if (wlen2 != wlen) {
3367 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003368 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003369 return NULL;
3370 }
3371
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003372 char *str;
3373 size_t error_pos;
3374 const char *reason;
3375 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
3376 current_locale, surrogateescape);
3377 if (res != 0) {
3378 if (res == -2) {
3379 PyObject *exc;
3380 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3381 "locale", unicode,
3382 (Py_ssize_t)error_pos,
3383 (Py_ssize_t)(error_pos+1),
3384 reason);
3385 if (exc != NULL) {
3386 PyCodec_StrictErrors(exc);
3387 Py_DECREF(exc);
3388 }
3389 return NULL;
Victor Stinner2cba6b82018-01-10 22:46:15 +01003390 }
3391 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003392 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003393 PyMem_Free(wstr);
3394 return NULL;
3395 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003396 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003397 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003399 PyObject *bytes = PyBytes_FromString(str);
3400 PyMem_RawFree(str);
3401 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003402}
3403
Victor Stinnerad158722010-10-27 00:25:46 +00003404PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003405PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3406{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003407 return unicode_encode_locale(unicode, errors, 1);
3408}
3409
3410PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003411PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003412{
Steve Dowercc16be82016-09-08 10:35:16 -07003413#if defined(__APPLE__)
3414 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003415#else
Victor Stinnercaba55b2018-08-03 15:33:52 +02003416 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner793b5312011-04-27 00:24:21 +02003417 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3418 cannot use it to encode and decode filenames before it is loaded. Load
3419 the Python codec requires to encode at least its own filename. Use the C
3420 version of the locale codec until the codec registry is initialized and
3421 the Python codec is loaded.
3422
3423 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3424 cannot only rely on it: check also interp->fscodec_initialized for
3425 subinterpreters. */
3426 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003427 return PyUnicode_AsEncodedString(unicode,
3428 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003429 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003430 }
3431 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003432 return unicode_encode_locale(unicode,
3433 Py_FileSystemDefaultEncodeErrors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003434 }
Victor Stinnerad158722010-10-27 00:25:46 +00003435#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003436}
3437
Alexander Belopolsky40018472011-02-26 01:02:56 +00003438PyObject *
3439PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003440 const char *encoding,
3441 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003442{
3443 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003444 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003445
Guido van Rossumd57fd912000-03-10 22:53:23 +00003446 if (!PyUnicode_Check(unicode)) {
3447 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003448 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003449 }
Fred Drakee4315f52000-05-09 19:53:39 +00003450
Victor Stinner942889a2016-09-05 15:40:10 -07003451 if (encoding == NULL) {
3452 return _PyUnicode_AsUTF8String(unicode, errors);
3453 }
3454
Fred Drakee4315f52000-05-09 19:53:39 +00003455 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003456 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3457 char *lower = buflower;
3458
3459 /* Fast paths */
3460 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3461 lower += 3;
3462 if (*lower == '_') {
3463 /* Match "utf8" and "utf_8" */
3464 lower++;
3465 }
3466
3467 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003468 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003469 }
3470 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3471 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3472 }
3473 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3474 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3475 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003476 }
Victor Stinner942889a2016-09-05 15:40:10 -07003477 else {
3478 if (strcmp(lower, "ascii") == 0
3479 || strcmp(lower, "us_ascii") == 0) {
3480 return _PyUnicode_AsASCIIString(unicode, errors);
3481 }
Steve Dowercc16be82016-09-08 10:35:16 -07003482#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003483 else if (strcmp(lower, "mbcs") == 0) {
3484 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3485 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003486#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003487 else if (strcmp(lower, "latin1") == 0 ||
3488 strcmp(lower, "latin_1") == 0 ||
3489 strcmp(lower, "iso_8859_1") == 0 ||
3490 strcmp(lower, "iso8859_1") == 0) {
3491 return _PyUnicode_AsLatin1String(unicode, errors);
3492 }
3493 }
Victor Stinner37296e82010-06-10 13:36:23 +00003494 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003495
3496 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003497 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003498 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003499 return NULL;
3500
3501 /* The normal path */
3502 if (PyBytes_Check(v))
3503 return v;
3504
3505 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003506 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003507 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003508 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003509
3510 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003511 "encoder %s returned bytearray instead of bytes; "
3512 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003513 encoding);
3514 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003515 Py_DECREF(v);
3516 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003517 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003518
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003519 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3520 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003521 Py_DECREF(v);
3522 return b;
3523 }
3524
3525 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003526 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3527 "use codecs.encode() to encode to arbitrary types",
3528 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003529 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003530 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003531 return NULL;
3532}
3533
Alexander Belopolsky40018472011-02-26 01:02:56 +00003534PyObject *
3535PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003536 const char *encoding,
3537 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003538{
3539 PyObject *v;
3540
3541 if (!PyUnicode_Check(unicode)) {
3542 PyErr_BadArgument();
3543 goto onError;
3544 }
3545
Serhiy Storchaka00939072016-10-27 21:05:49 +03003546 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3547 "PyUnicode_AsEncodedUnicode() is deprecated; "
3548 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3549 return NULL;
3550
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003551 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003552 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003553
3554 /* Encode via the codec registry */
3555 v = PyCodec_Encode(unicode, encoding, errors);
3556 if (v == NULL)
3557 goto onError;
3558 if (!PyUnicode_Check(v)) {
3559 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003560 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3561 "use codecs.encode() to encode to arbitrary types",
3562 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003563 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003564 Py_DECREF(v);
3565 goto onError;
3566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003567 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003568
Benjamin Peterson29060642009-01-31 22:14:21 +00003569 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003570 return NULL;
3571}
3572
Victor Stinner2cba6b82018-01-10 22:46:15 +01003573static PyObject*
3574unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3575 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003576{
Victor Stinner1b579672011-12-17 05:47:23 +01003577 int surrogateescape;
Victor Stinner1b579672011-12-17 05:47:23 +01003578 if (locale_error_handler(errors, &surrogateescape) < 0)
3579 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003580
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003581 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3582 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003583 return NULL;
3584 }
3585
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003586 wchar_t *wstr;
3587 size_t wlen;
3588 const char *reason;
3589 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
3590 current_locale, surrogateescape);
3591 if (res != 0) {
3592 if (res == -2) {
3593 PyObject *exc;
3594 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3595 "locale", str, len,
3596 (Py_ssize_t)wlen,
3597 (Py_ssize_t)(wlen + 1),
3598 reason);
3599 if (exc != NULL) {
3600 PyCodec_StrictErrors(exc);
3601 Py_DECREF(exc);
3602 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003603 }
3604 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003605 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003606 }
Victor Stinner2f197072011-12-17 07:08:30 +01003607 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003608 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003609
3610 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3611 PyMem_RawFree(wstr);
3612 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003613}
3614
3615PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003616PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3617 const char *errors)
3618{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003619 return unicode_decode_locale(str, len, errors, 1);
3620}
3621
3622PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003623PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003624{
3625 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003626 return unicode_decode_locale(str, size, errors, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003627}
3628
3629
3630PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003631PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003632 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003633 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3634}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003635
Christian Heimes5894ba72007-11-04 11:43:14 +00003636PyObject*
3637PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3638{
Steve Dowercc16be82016-09-08 10:35:16 -07003639#if defined(__APPLE__)
3640 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003641#else
Victor Stinnercaba55b2018-08-03 15:33:52 +02003642 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner793b5312011-04-27 00:24:21 +02003643 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3644 cannot use it to encode and decode filenames before it is loaded. Load
3645 the Python codec requires to encode at least its own filename. Use the C
3646 version of the locale codec until the codec registry is initialized and
3647 the Python codec is loaded.
3648
3649 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3650 cannot only rely on it: check also interp->fscodec_initialized for
3651 subinterpreters. */
3652 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003653 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003654 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003655 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003656 }
3657 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003658 return unicode_decode_locale(s, size,
3659 Py_FileSystemDefaultEncodeErrors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003660 }
Victor Stinnerad158722010-10-27 00:25:46 +00003661#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003662}
3663
Martin v. Löwis011e8422009-05-05 04:43:17 +00003664
3665int
3666PyUnicode_FSConverter(PyObject* arg, void* addr)
3667{
Brett Cannonec6ce872016-09-06 15:50:29 -07003668 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003669 PyObject *output = NULL;
3670 Py_ssize_t size;
3671 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003672 if (arg == NULL) {
3673 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003674 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003675 return 1;
3676 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003677 path = PyOS_FSPath(arg);
3678 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003679 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003680 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003681 if (PyBytes_Check(path)) {
3682 output = path;
3683 }
3684 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3685 output = PyUnicode_EncodeFSDefault(path);
3686 Py_DECREF(path);
3687 if (!output) {
3688 return 0;
3689 }
3690 assert(PyBytes_Check(output));
3691 }
3692
Victor Stinner0ea2a462010-04-30 00:22:08 +00003693 size = PyBytes_GET_SIZE(output);
3694 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003695 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003696 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003697 Py_DECREF(output);
3698 return 0;
3699 }
3700 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003701 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003702}
3703
3704
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003705int
3706PyUnicode_FSDecoder(PyObject* arg, void* addr)
3707{
Brett Cannona5711202016-09-06 19:36:01 -07003708 int is_buffer = 0;
3709 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003710 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003711 if (arg == NULL) {
3712 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003713 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003714 return 1;
3715 }
Brett Cannona5711202016-09-06 19:36:01 -07003716
3717 is_buffer = PyObject_CheckBuffer(arg);
3718 if (!is_buffer) {
3719 path = PyOS_FSPath(arg);
3720 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003721 return 0;
3722 }
Brett Cannona5711202016-09-06 19:36:01 -07003723 }
3724 else {
3725 path = arg;
3726 Py_INCREF(arg);
3727 }
3728
3729 if (PyUnicode_Check(path)) {
Brett Cannona5711202016-09-06 19:36:01 -07003730 output = path;
3731 }
3732 else if (PyBytes_Check(path) || is_buffer) {
3733 PyObject *path_bytes = NULL;
3734
3735 if (!PyBytes_Check(path) &&
3736 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3737 "path should be string, bytes, or os.PathLike, not %.200s",
3738 Py_TYPE(arg)->tp_name)) {
3739 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003740 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003741 }
3742 path_bytes = PyBytes_FromObject(path);
3743 Py_DECREF(path);
3744 if (!path_bytes) {
3745 return 0;
3746 }
3747 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3748 PyBytes_GET_SIZE(path_bytes));
3749 Py_DECREF(path_bytes);
3750 if (!output) {
3751 return 0;
3752 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003753 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003754 else {
3755 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003756 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003757 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003758 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003759 return 0;
3760 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003761 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003762 Py_DECREF(output);
3763 return 0;
3764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003765 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003766 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003767 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003768 Py_DECREF(output);
3769 return 0;
3770 }
3771 *(PyObject**)addr = output;
3772 return Py_CLEANUP_SUPPORTED;
3773}
3774
3775
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003776const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003778{
Christian Heimesf3863112007-11-22 07:46:41 +00003779 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003781 if (!PyUnicode_Check(unicode)) {
3782 PyErr_BadArgument();
3783 return NULL;
3784 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003785 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003786 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003787
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003788 if (PyUnicode_UTF8(unicode) == NULL) {
3789 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003790 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791 if (bytes == NULL)
3792 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003793 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3794 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003795 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003796 Py_DECREF(bytes);
3797 return NULL;
3798 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003799 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003800 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003801 PyBytes_AS_STRING(bytes),
3802 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003803 Py_DECREF(bytes);
3804 }
3805
3806 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003807 *psize = PyUnicode_UTF8_LENGTH(unicode);
3808 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003809}
3810
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003811const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003814 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3815}
3816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003817Py_UNICODE *
3818PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3819{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003820 const unsigned char *one_byte;
3821#if SIZEOF_WCHAR_T == 4
3822 const Py_UCS2 *two_bytes;
3823#else
3824 const Py_UCS4 *four_bytes;
3825 const Py_UCS4 *ucs4_end;
3826 Py_ssize_t num_surrogates;
3827#endif
3828 wchar_t *w;
3829 wchar_t *wchar_end;
3830
3831 if (!PyUnicode_Check(unicode)) {
3832 PyErr_BadArgument();
3833 return NULL;
3834 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003835 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003837 assert(_PyUnicode_KIND(unicode) != 0);
3838 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003842 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3843 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 num_surrogates = 0;
3845
3846 for (; four_bytes < ucs4_end; ++four_bytes) {
3847 if (*four_bytes > 0xFFFF)
3848 ++num_surrogates;
3849 }
3850
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003851 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3852 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3853 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003854 PyErr_NoMemory();
3855 return NULL;
3856 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003857 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003858
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003859 w = _PyUnicode_WSTR(unicode);
3860 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3861 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3863 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003864 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003866 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3867 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003868 }
3869 else
3870 *w = *four_bytes;
3871
3872 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07003873 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 }
3875 }
3876 *w = 0;
3877#else
3878 /* sizeof(wchar_t) == 4 */
3879 Py_FatalError("Impossible unicode object state, wstr and str "
3880 "should share memory already.");
3881 return NULL;
3882#endif
3883 }
3884 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003885 if ((size_t)_PyUnicode_LENGTH(unicode) >
3886 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3887 PyErr_NoMemory();
3888 return NULL;
3889 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003890 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3891 (_PyUnicode_LENGTH(unicode) + 1));
3892 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893 PyErr_NoMemory();
3894 return NULL;
3895 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003896 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3897 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3898 w = _PyUnicode_WSTR(unicode);
3899 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003900
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003901 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3902 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003903 for (; w < wchar_end; ++one_byte, ++w)
3904 *w = *one_byte;
3905 /* null-terminate the wstr */
3906 *w = 0;
3907 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003908 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003910 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911 for (; w < wchar_end; ++two_bytes, ++w)
3912 *w = *two_bytes;
3913 /* null-terminate the wstr */
3914 *w = 0;
3915#else
3916 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003917 PyObject_FREE(_PyUnicode_WSTR(unicode));
3918 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003919 Py_FatalError("Impossible unicode object state, wstr "
3920 "and str should share memory already.");
3921 return NULL;
3922#endif
3923 }
3924 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07003925 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 }
3927 }
3928 }
3929 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003930 *size = PyUnicode_WSTR_LENGTH(unicode);
3931 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003932}
3933
Alexander Belopolsky40018472011-02-26 01:02:56 +00003934Py_UNICODE *
3935PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003936{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003937 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003938}
3939
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03003940const Py_UNICODE *
3941_PyUnicode_AsUnicode(PyObject *unicode)
3942{
3943 Py_ssize_t size;
3944 const Py_UNICODE *wstr;
3945
3946 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
3947 if (wstr && wcslen(wstr) != (size_t)size) {
3948 PyErr_SetString(PyExc_ValueError, "embedded null character");
3949 return NULL;
3950 }
3951 return wstr;
3952}
3953
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954
Alexander Belopolsky40018472011-02-26 01:02:56 +00003955Py_ssize_t
3956PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003957{
3958 if (!PyUnicode_Check(unicode)) {
3959 PyErr_BadArgument();
3960 goto onError;
3961 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003962 if (_PyUnicode_WSTR(unicode) == NULL) {
3963 if (PyUnicode_AsUnicode(unicode) == NULL)
3964 goto onError;
3965 }
3966 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003967
Benjamin Peterson29060642009-01-31 22:14:21 +00003968 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003969 return -1;
3970}
3971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003972Py_ssize_t
3973PyUnicode_GetLength(PyObject *unicode)
3974{
Victor Stinner07621332012-06-16 04:53:46 +02003975 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003976 PyErr_BadArgument();
3977 return -1;
3978 }
Victor Stinner07621332012-06-16 04:53:46 +02003979 if (PyUnicode_READY(unicode) == -1)
3980 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981 return PyUnicode_GET_LENGTH(unicode);
3982}
3983
3984Py_UCS4
3985PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3986{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003987 void *data;
3988 int kind;
3989
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003990 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003991 PyErr_BadArgument();
3992 return (Py_UCS4)-1;
3993 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003994 if (PyUnicode_READY(unicode) == -1) {
3995 return (Py_UCS4)-1;
3996 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003997 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003998 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999 return (Py_UCS4)-1;
4000 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004001 data = PyUnicode_DATA(unicode);
4002 kind = PyUnicode_KIND(unicode);
4003 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004}
4005
4006int
4007PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4008{
4009 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004010 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011 return -1;
4012 }
Victor Stinner488fa492011-12-12 00:01:39 +01004013 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004014 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004015 PyErr_SetString(PyExc_IndexError, "string index out of range");
4016 return -1;
4017 }
Victor Stinner488fa492011-12-12 00:01:39 +01004018 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004019 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004020 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4021 PyErr_SetString(PyExc_ValueError, "character out of range");
4022 return -1;
4023 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4025 index, ch);
4026 return 0;
4027}
4028
Alexander Belopolsky40018472011-02-26 01:02:56 +00004029const char *
4030PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004031{
Victor Stinner42cb4622010-09-01 19:39:01 +00004032 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004033}
4034
Victor Stinner554f3f02010-06-16 23:33:54 +00004035/* create or adjust a UnicodeDecodeError */
4036static void
4037make_decode_exception(PyObject **exceptionObject,
4038 const char *encoding,
4039 const char *input, Py_ssize_t length,
4040 Py_ssize_t startpos, Py_ssize_t endpos,
4041 const char *reason)
4042{
4043 if (*exceptionObject == NULL) {
4044 *exceptionObject = PyUnicodeDecodeError_Create(
4045 encoding, input, length, startpos, endpos, reason);
4046 }
4047 else {
4048 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4049 goto onError;
4050 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4051 goto onError;
4052 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4053 goto onError;
4054 }
4055 return;
4056
4057onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004058 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004059}
4060
Steve Dowercc16be82016-09-08 10:35:16 -07004061#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004062/* error handling callback helper:
4063 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004064 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004065 and adjust various state variables.
4066 return 0 on success, -1 on error
4067*/
4068
Alexander Belopolsky40018472011-02-26 01:02:56 +00004069static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004070unicode_decode_call_errorhandler_wchar(
4071 const char *errors, PyObject **errorHandler,
4072 const char *encoding, const char *reason,
4073 const char **input, const char **inend, Py_ssize_t *startinpos,
4074 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4075 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004076{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004077 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004078
4079 PyObject *restuple = NULL;
4080 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004081 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004082 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004083 Py_ssize_t requiredsize;
4084 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004085 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004086 wchar_t *repwstr;
4087 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004088
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004089 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4090 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004091
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004093 *errorHandler = PyCodec_LookupError(errors);
4094 if (*errorHandler == NULL)
4095 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004096 }
4097
Victor Stinner554f3f02010-06-16 23:33:54 +00004098 make_decode_exception(exceptionObject,
4099 encoding,
4100 *input, *inend - *input,
4101 *startinpos, *endinpos,
4102 reason);
4103 if (*exceptionObject == NULL)
4104 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004105
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004106 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004107 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004108 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004109 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004110 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004111 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004112 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004113 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004114 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004115
4116 /* Copy back the bytes variables, which might have been modified by the
4117 callback */
4118 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4119 if (!inputobj)
4120 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004121 *input = PyBytes_AS_STRING(inputobj);
4122 insize = PyBytes_GET_SIZE(inputobj);
4123 *inend = *input + insize;
4124 /* we can DECREF safely, as the exception has another reference,
4125 so the object won't go away. */
4126 Py_DECREF(inputobj);
4127
4128 if (newpos<0)
4129 newpos = insize+newpos;
4130 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004131 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004132 goto onError;
4133 }
4134
4135 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4136 if (repwstr == NULL)
4137 goto onError;
4138 /* need more space? (at least enough for what we
4139 have+the replacement+the rest of the string (starting
4140 at the new input position), so we won't have to check space
4141 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004142 requiredsize = *outpos;
4143 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4144 goto overflow;
4145 requiredsize += repwlen;
4146 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4147 goto overflow;
4148 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004149 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004150 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004151 requiredsize = 2*outsize;
4152 if (unicode_resize(output, requiredsize) < 0)
4153 goto onError;
4154 }
4155 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4156 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004157 *endinpos = newpos;
4158 *inptr = *input + newpos;
4159
4160 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004161 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004162 return 0;
4163
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004164 overflow:
4165 PyErr_SetString(PyExc_OverflowError,
4166 "decoded result is too long for a Python string");
4167
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004168 onError:
4169 Py_XDECREF(restuple);
4170 return -1;
4171}
Steve Dowercc16be82016-09-08 10:35:16 -07004172#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004173
4174static int
4175unicode_decode_call_errorhandler_writer(
4176 const char *errors, PyObject **errorHandler,
4177 const char *encoding, const char *reason,
4178 const char **input, const char **inend, Py_ssize_t *startinpos,
4179 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4180 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4181{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004182 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004183
4184 PyObject *restuple = NULL;
4185 PyObject *repunicode = NULL;
4186 Py_ssize_t insize;
4187 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004188 Py_ssize_t replen;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004189 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004190 PyObject *inputobj = NULL;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004191 int need_to_grow = 0;
4192 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004193
4194 if (*errorHandler == NULL) {
4195 *errorHandler = PyCodec_LookupError(errors);
4196 if (*errorHandler == NULL)
4197 goto onError;
4198 }
4199
4200 make_decode_exception(exceptionObject,
4201 encoding,
4202 *input, *inend - *input,
4203 *startinpos, *endinpos,
4204 reason);
4205 if (*exceptionObject == NULL)
4206 goto onError;
4207
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004208 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004209 if (restuple == NULL)
4210 goto onError;
4211 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004212 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004213 goto onError;
4214 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004215 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004216 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004217
4218 /* Copy back the bytes variables, which might have been modified by the
4219 callback */
4220 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4221 if (!inputobj)
4222 goto onError;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004223 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004224 *input = PyBytes_AS_STRING(inputobj);
4225 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004226 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004227 /* we can DECREF safely, as the exception has another reference,
4228 so the object won't go away. */
4229 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004230
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004231 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004232 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004233 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004234 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004235 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004236 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004237
Victor Stinner170ca6f2013-04-18 00:25:28 +02004238 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004239 if (replen > 1) {
4240 writer->min_length += replen - 1;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004241 need_to_grow = 1;
4242 }
4243 new_inptr = *input + newpos;
4244 if (*inend - new_inptr > remain) {
4245 /* We don't know the decoding algorithm here so we make the worst
4246 assumption that one byte decodes to one unicode character.
4247 If unfortunately one byte could decode to more unicode characters,
4248 the decoder may write out-of-bound then. Is it possible for the
4249 algorithms using this function? */
4250 writer->min_length += *inend - new_inptr - remain;
4251 need_to_grow = 1;
4252 }
4253 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004254 writer->overallocate = 1;
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02004255 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004256 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4257 goto onError;
4258 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004259 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004260 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004261
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004262 *endinpos = newpos;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004263 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004264
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004265 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004266 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004267 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004268
Benjamin Peterson29060642009-01-31 22:14:21 +00004269 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004270 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004271 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004272}
4273
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004274/* --- UTF-7 Codec -------------------------------------------------------- */
4275
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276/* See RFC2152 for details. We encode conservatively and decode liberally. */
4277
4278/* Three simple macros defining base-64. */
4279
4280/* Is c a base-64 character? */
4281
4282#define IS_BASE64(c) \
4283 (((c) >= 'A' && (c) <= 'Z') || \
4284 ((c) >= 'a' && (c) <= 'z') || \
4285 ((c) >= '0' && (c) <= '9') || \
4286 (c) == '+' || (c) == '/')
4287
4288/* given that c is a base-64 character, what is its base-64 value? */
4289
4290#define FROM_BASE64(c) \
4291 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4292 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4293 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4294 (c) == '+' ? 62 : 63)
4295
4296/* What is the base-64 character of the bottom 6 bits of n? */
4297
4298#define TO_BASE64(n) \
4299 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4300
4301/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4302 * decoded as itself. We are permissive on decoding; the only ASCII
4303 * byte not decoding to itself is the + which begins a base64
4304 * string. */
4305
4306#define DECODE_DIRECT(c) \
4307 ((c) <= 127 && (c) != '+')
4308
4309/* The UTF-7 encoder treats ASCII characters differently according to
4310 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4311 * the above). See RFC2152. This array identifies these different
4312 * sets:
4313 * 0 : "Set D"
4314 * alphanumeric and '(),-./:?
4315 * 1 : "Set O"
4316 * !"#$%&*;<=>@[]^_`{|}
4317 * 2 : "whitespace"
4318 * ht nl cr sp
4319 * 3 : special (must be base64 encoded)
4320 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4321 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322
Tim Petersced69f82003-09-16 20:30:58 +00004323static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324char utf7_category[128] = {
4325/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4326 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4327/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4328 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4329/* sp ! " # $ % & ' ( ) * + , - . / */
4330 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4331/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4332 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4333/* @ A B C D E F G H I J K L M N O */
4334 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4335/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4336 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4337/* ` a b c d e f g h i j k l m n o */
4338 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4339/* p q r s t u v w x y z { | } ~ del */
4340 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341};
4342
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343/* ENCODE_DIRECT: this character should be encoded as itself. The
4344 * answer depends on whether we are encoding set O as itself, and also
4345 * on whether we are encoding whitespace as itself. RFC2152 makes it
4346 * clear that the answers to these questions vary between
4347 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004348
Antoine Pitrou244651a2009-05-04 18:56:13 +00004349#define ENCODE_DIRECT(c, directO, directWS) \
4350 ((c) < 128 && (c) > 0 && \
4351 ((utf7_category[(c)] == 0) || \
4352 (directWS && (utf7_category[(c)] == 2)) || \
4353 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004354
Alexander Belopolsky40018472011-02-26 01:02:56 +00004355PyObject *
4356PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004357 Py_ssize_t size,
4358 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004359{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004360 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4361}
4362
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363/* The decoder. The only state we preserve is our read position,
4364 * i.e. how many characters we have consumed. So if we end in the
4365 * middle of a shift sequence we have to back off the read position
4366 * and the output to the beginning of the sequence, otherwise we lose
4367 * all the shift state (seen bits, number of bits seen, high
4368 * surrogate). */
4369
Alexander Belopolsky40018472011-02-26 01:02:56 +00004370PyObject *
4371PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004372 Py_ssize_t size,
4373 const char *errors,
4374 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004375{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004376 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004377 Py_ssize_t startinpos;
4378 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004379 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004380 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 const char *errmsg = "";
4382 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004383 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004384 unsigned int base64bits = 0;
4385 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004386 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004387 PyObject *errorHandler = NULL;
4388 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004389
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004390 if (size == 0) {
4391 if (consumed)
4392 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004393 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004394 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004396 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004397 _PyUnicodeWriter_Init(&writer);
4398 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004399
4400 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 e = s + size;
4402
4403 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004404 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004406 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407
Antoine Pitrou244651a2009-05-04 18:56:13 +00004408 if (inShift) { /* in a base-64 section */
4409 if (IS_BASE64(ch)) { /* consume a base-64 character */
4410 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4411 base64bits += 6;
4412 s++;
4413 if (base64bits >= 16) {
4414 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004415 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004416 base64bits -= 16;
4417 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004418 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 if (surrogate) {
4420 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004421 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4422 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004423 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004424 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004426 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004427 }
4428 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004429 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004430 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 }
4433 }
Victor Stinner551ac952011-11-29 22:58:13 +01004434 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004435 /* first surrogate */
4436 surrogate = outCh;
4437 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004439 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004440 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004441 }
4442 }
4443 }
4444 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004445 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004446 if (base64bits > 0) { /* left-over bits */
4447 if (base64bits >= 6) {
4448 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004449 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004450 errmsg = "partial character in shift sequence";
4451 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 else {
4454 /* Some bits remain; they should be zero */
4455 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004456 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 errmsg = "non-zero padding bits in shift sequence";
4458 goto utf7Error;
4459 }
4460 }
4461 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004462 if (surrogate && DECODE_DIRECT(ch)) {
4463 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4464 goto onError;
4465 }
4466 surrogate = 0;
4467 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 /* '-' is absorbed; other terminating
4469 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004470 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472 }
4473 }
4474 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004475 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476 s++; /* consume '+' */
4477 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004478 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004479 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004480 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004481 }
Zackery Spytze349bf22018-08-18 22:43:38 -06004482 else if (s < e && !IS_BASE64(*s)) {
4483 s++;
4484 errmsg = "ill-formed sequence";
4485 goto utf7Error;
4486 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004489 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004490 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004491 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004492 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004493 }
4494 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004496 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004497 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004498 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004500 else {
4501 startinpos = s-starts;
4502 s++;
4503 errmsg = "unexpected special character";
4504 goto utf7Error;
4505 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004508 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004509 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 errors, &errorHandler,
4511 "utf7", errmsg,
4512 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004513 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004514 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515 }
4516
Antoine Pitrou244651a2009-05-04 18:56:13 +00004517 /* end of string */
4518
4519 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4520 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004521 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004522 if (surrogate ||
4523 (base64bits >= 6) ||
4524 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004525 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004526 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527 errors, &errorHandler,
4528 "utf7", "unterminated shift sequence",
4529 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004530 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004531 goto onError;
4532 if (s < e)
4533 goto restart;
4534 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004535 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004536
4537 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004538 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004540 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004541 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004542 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004543 writer.kind, writer.data, shiftOutStart);
4544 Py_XDECREF(errorHandler);
4545 Py_XDECREF(exc);
4546 _PyUnicodeWriter_Dealloc(&writer);
4547 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004548 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004549 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004550 }
4551 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004552 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004553 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004554 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004556 Py_XDECREF(errorHandler);
4557 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004558 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004559
Benjamin Peterson29060642009-01-31 22:14:21 +00004560 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004561 Py_XDECREF(errorHandler);
4562 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004563 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004564 return NULL;
4565}
4566
4567
Alexander Belopolsky40018472011-02-26 01:02:56 +00004568PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004569_PyUnicode_EncodeUTF7(PyObject *str,
4570 int base64SetO,
4571 int base64WhiteSpace,
4572 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004573{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004574 int kind;
4575 void *data;
4576 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004577 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004578 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004579 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 unsigned int base64bits = 0;
4581 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004582 char * out;
4583 char * start;
4584
Benjamin Petersonbac79492012-01-14 13:34:47 -05004585 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004586 return NULL;
4587 kind = PyUnicode_KIND(str);
4588 data = PyUnicode_DATA(str);
4589 len = PyUnicode_GET_LENGTH(str);
4590
4591 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004592 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004593
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004594 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004595 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004596 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004597 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598 if (v == NULL)
4599 return NULL;
4600
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004601 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004602 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004603 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004604
Antoine Pitrou244651a2009-05-04 18:56:13 +00004605 if (inShift) {
4606 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4607 /* shifting out */
4608 if (base64bits) { /* output remaining bits */
4609 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4610 base64buffer = 0;
4611 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004612 }
4613 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004614 /* Characters not in the BASE64 set implicitly unshift the sequence
4615 so no '-' is required, except if the character is itself a '-' */
4616 if (IS_BASE64(ch) || ch == '-') {
4617 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004618 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004619 *out++ = (char) ch;
4620 }
4621 else {
4622 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004623 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004624 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004625 else { /* not in a shift sequence */
4626 if (ch == '+') {
4627 *out++ = '+';
4628 *out++ = '-';
4629 }
4630 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4631 *out++ = (char) ch;
4632 }
4633 else {
4634 *out++ = '+';
4635 inShift = 1;
4636 goto encode_char;
4637 }
4638 }
4639 continue;
4640encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004641 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004642 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004643
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 /* code first surrogate */
4645 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004646 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004647 while (base64bits >= 6) {
4648 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4649 base64bits -= 6;
4650 }
4651 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004652 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004653 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004654 base64bits += 16;
4655 base64buffer = (base64buffer << 16) | ch;
4656 while (base64bits >= 6) {
4657 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4658 base64bits -= 6;
4659 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004660 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661 if (base64bits)
4662 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4663 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004664 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004665 if (_PyBytes_Resize(&v, out - start) < 0)
4666 return NULL;
4667 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004668}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004669PyObject *
4670PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4671 Py_ssize_t size,
4672 int base64SetO,
4673 int base64WhiteSpace,
4674 const char *errors)
4675{
4676 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004677 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004678 if (tmp == NULL)
4679 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004680 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004681 base64WhiteSpace, errors);
4682 Py_DECREF(tmp);
4683 return result;
4684}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004685
Antoine Pitrou244651a2009-05-04 18:56:13 +00004686#undef IS_BASE64
4687#undef FROM_BASE64
4688#undef TO_BASE64
4689#undef DECODE_DIRECT
4690#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004691
Guido van Rossumd57fd912000-03-10 22:53:23 +00004692/* --- UTF-8 Codec -------------------------------------------------------- */
4693
Alexander Belopolsky40018472011-02-26 01:02:56 +00004694PyObject *
4695PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004696 Py_ssize_t size,
4697 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004698{
Walter Dörwald69652032004-09-07 20:24:22 +00004699 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4700}
4701
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004702#include "stringlib/asciilib.h"
4703#include "stringlib/codecs.h"
4704#include "stringlib/undef.h"
4705
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004706#include "stringlib/ucs1lib.h"
4707#include "stringlib/codecs.h"
4708#include "stringlib/undef.h"
4709
4710#include "stringlib/ucs2lib.h"
4711#include "stringlib/codecs.h"
4712#include "stringlib/undef.h"
4713
4714#include "stringlib/ucs4lib.h"
4715#include "stringlib/codecs.h"
4716#include "stringlib/undef.h"
4717
Antoine Pitrouab868312009-01-10 15:40:25 +00004718/* Mask to quickly check whether a C 'long' contains a
4719 non-ASCII, UTF8-encoded char. */
4720#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004721# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004722#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004723# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004724#else
4725# error C 'long' size should be either 4 or 8!
4726#endif
4727
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004728static Py_ssize_t
4729ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004730{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004732 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004733
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004734 /*
4735 * Issue #17237: m68k is a bit different from most architectures in
4736 * that objects do not use "natural alignment" - for example, int and
4737 * long are only aligned at 2-byte boundaries. Therefore the assert()
4738 * won't work; also, tests have shown that skipping the "optimised
4739 * version" will even speed up m68k.
4740 */
4741#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004742#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004743 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4744 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 /* Fast path, see in STRINGLIB(utf8_decode) for
4746 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004747 /* Help allocation */
4748 const char *_p = p;
4749 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 while (_p < aligned_end) {
4751 unsigned long value = *(const unsigned long *) _p;
4752 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004753 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004754 *((unsigned long *)q) = value;
4755 _p += SIZEOF_LONG;
4756 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004757 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 p = _p;
4759 while (p < end) {
4760 if ((unsigned char)*p & 0x80)
4761 break;
4762 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004763 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004764 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004765 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004767#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004768 while (p < end) {
4769 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4770 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004771 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004772 /* Help allocation */
4773 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004774 while (_p < aligned_end) {
4775 unsigned long value = *(unsigned long *) _p;
4776 if (value & ASCII_CHAR_MASK)
4777 break;
4778 _p += SIZEOF_LONG;
4779 }
4780 p = _p;
4781 if (_p == end)
4782 break;
4783 }
4784 if ((unsigned char)*p & 0x80)
4785 break;
4786 ++p;
4787 }
4788 memcpy(dest, start, p - start);
4789 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004790}
Antoine Pitrouab868312009-01-10 15:40:25 +00004791
Victor Stinner785938e2011-12-11 20:09:03 +01004792PyObject *
4793PyUnicode_DecodeUTF8Stateful(const char *s,
4794 Py_ssize_t size,
4795 const char *errors,
4796 Py_ssize_t *consumed)
4797{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004798 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004799 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004801
4802 Py_ssize_t startinpos;
4803 Py_ssize_t endinpos;
4804 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004805 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004806 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004807 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004808
4809 if (size == 0) {
4810 if (consumed)
4811 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004812 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004813 }
4814
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004815 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4816 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004817 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004818 *consumed = 1;
4819 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004820 }
4821
Victor Stinner8f674cc2013-04-17 23:02:17 +02004822 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004823 writer.min_length = size;
4824 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004825 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004826
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004827 writer.pos = ascii_decode(s, end, writer.data);
4828 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004829 while (s < end) {
4830 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004831 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004832
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004833 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004834 if (PyUnicode_IS_ASCII(writer.buffer))
4835 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004836 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004837 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004838 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004839 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004840 } else {
4841 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004842 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 }
4844
4845 switch (ch) {
4846 case 0:
4847 if (s == end || consumed)
4848 goto End;
4849 errmsg = "unexpected end of data";
4850 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004851 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004852 break;
4853 case 1:
4854 errmsg = "invalid start byte";
4855 startinpos = s - starts;
4856 endinpos = startinpos + 1;
4857 break;
4858 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004859 case 3:
4860 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004861 errmsg = "invalid continuation byte";
4862 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004863 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004864 break;
4865 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004866 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 goto onError;
4868 continue;
4869 }
4870
Victor Stinner1d65d912015-10-05 13:43:50 +02004871 if (error_handler == _Py_ERROR_UNKNOWN)
4872 error_handler = get_error_handler(errors);
4873
4874 switch (error_handler) {
4875 case _Py_ERROR_IGNORE:
4876 s += (endinpos - startinpos);
4877 break;
4878
4879 case _Py_ERROR_REPLACE:
4880 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4881 goto onError;
4882 s += (endinpos - startinpos);
4883 break;
4884
4885 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004886 {
4887 Py_ssize_t i;
4888
Victor Stinner1d65d912015-10-05 13:43:50 +02004889 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4890 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004891 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004892 ch = (Py_UCS4)(unsigned char)(starts[i]);
4893 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4894 ch + 0xdc00);
4895 writer.pos++;
4896 }
4897 s += (endinpos - startinpos);
4898 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004899 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004900
4901 default:
4902 if (unicode_decode_call_errorhandler_writer(
4903 errors, &error_handler_obj,
4904 "utf-8", errmsg,
4905 &starts, &end, &startinpos, &endinpos, &exc, &s,
4906 &writer))
4907 goto onError;
4908 }
Victor Stinner785938e2011-12-11 20:09:03 +01004909 }
4910
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004912 if (consumed)
4913 *consumed = s - starts;
4914
Victor Stinner1d65d912015-10-05 13:43:50 +02004915 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004916 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004917 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918
4919onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004920 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004921 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004922 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004923 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004924}
4925
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004926
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004927/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4928 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004929
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004930 On success, write a pointer to a newly allocated wide character string into
4931 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4932 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004933
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004934 On memory allocation failure, return -1.
4935
4936 On decoding error (if surrogateescape is zero), return -2. If wlen is
4937 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4938 is not NULL, write the decoding error message into *reason. */
4939int
4940_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
4941 const char **reason, int surrogateescape)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004942{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004943 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004944 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004945 wchar_t *unicode;
4946 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004947
4948 /* Note: size will always be longer than the resulting Unicode
4949 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004950 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004951 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004952 }
4953
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004954 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004955 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004956 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004957 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004958
4959 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004960 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004961 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004962 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004963 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004964#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004965 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004966#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004967 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004968#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004969 if (ch > 0xFF) {
4970#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07004971 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004972#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02004973 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004974 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004975 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4976 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4977#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004978 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004979 else {
4980 if (!ch && s == e)
4981 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004982 if (!surrogateescape) {
4983 PyMem_RawFree(unicode );
4984 if (reason != NULL) {
4985 switch (ch) {
4986 case 0:
4987 *reason = "unexpected end of data";
4988 break;
4989 case 1:
4990 *reason = "invalid start byte";
4991 break;
4992 /* 2, 3, 4 */
4993 default:
4994 *reason = "invalid continuation byte";
4995 break;
4996 }
4997 }
4998 if (wlen != NULL) {
4999 *wlen = s - orig_s;
5000 }
5001 return -2;
5002 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005003 /* surrogateescape */
5004 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5005 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005006 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005007 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005008 if (wlen) {
5009 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005010 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005011 *wstr = unicode;
5012 return 0;
5013}
5014
5015wchar_t*
5016_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen)
5017{
5018 wchar_t *wstr;
5019 int res = _Py_DecodeUTF8Ex(arg, arglen, &wstr, NULL, NULL, 1);
5020 if (res != 0) {
5021 return NULL;
5022 }
5023 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005024}
5025
Antoine Pitrouab868312009-01-10 15:40:25 +00005026
Victor Stinnere47e6982017-12-21 15:45:16 +01005027/* UTF-8 encoder using the surrogateescape error handler .
5028
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005029 On success, return 0 and write the newly allocated character string (use
5030 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005031
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005032 On encoding failure, return -2 and write the position of the invalid
5033 surrogate character into *error_pos (if error_pos is set) and the decoding
5034 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005035
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005036 On memory allocation failure, return -1. */
5037int
5038_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
5039 const char **reason, int raw_malloc, int surrogateescape)
Victor Stinnere47e6982017-12-21 15:45:16 +01005040{
5041 const Py_ssize_t max_char_size = 4;
5042 Py_ssize_t len = wcslen(text);
5043
5044 assert(len >= 0);
5045
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005046 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5047 return -1;
5048 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005049 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005050 if (raw_malloc) {
5051 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005052 }
5053 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005054 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005055 }
5056 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005057 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005058 }
5059
5060 char *p = bytes;
5061 Py_ssize_t i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005062 for (i = 0; i < len; i++) {
5063 Py_UCS4 ch = text[i];
Victor Stinnere47e6982017-12-21 15:45:16 +01005064
5065 if (ch < 0x80) {
5066 /* Encode ASCII */
5067 *p++ = (char) ch;
5068
5069 }
5070 else if (ch < 0x0800) {
5071 /* Encode Latin-1 */
5072 *p++ = (char)(0xc0 | (ch >> 6));
5073 *p++ = (char)(0x80 | (ch & 0x3f));
5074 }
5075 else if (Py_UNICODE_IS_SURROGATE(ch)) {
5076 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005077 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005078 if (error_pos != NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005079 *error_pos = (size_t)i;
Victor Stinnere47e6982017-12-21 15:45:16 +01005080 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005081 if (reason != NULL) {
5082 *reason = "encoding error";
5083 }
5084 if (raw_malloc) {
5085 PyMem_RawFree(bytes);
5086 }
5087 else {
5088 PyMem_Free(bytes);
5089 }
5090 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005091 }
5092 *p++ = (char)(ch & 0xff);
5093 }
5094 else if (ch < 0x10000) {
5095 *p++ = (char)(0xe0 | (ch >> 12));
5096 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5097 *p++ = (char)(0x80 | (ch & 0x3f));
5098 }
5099 else { /* ch >= 0x10000 */
5100 assert(ch <= MAX_UNICODE);
5101 /* Encode UCS4 Unicode ordinals */
5102 *p++ = (char)(0xf0 | (ch >> 18));
5103 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5104 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5105 *p++ = (char)(0x80 | (ch & 0x3f));
5106 }
5107 }
5108 *p++ = '\0';
5109
5110 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005111 char *bytes2;
5112 if (raw_malloc) {
5113 bytes2 = PyMem_RawRealloc(bytes, final_size);
5114 }
5115 else {
5116 bytes2 = PyMem_Realloc(bytes, final_size);
5117 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005118 if (bytes2 == NULL) {
5119 if (error_pos != NULL) {
5120 *error_pos = (size_t)-1;
5121 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005122 if (raw_malloc) {
5123 PyMem_RawFree(bytes);
5124 }
5125 else {
5126 PyMem_Free(bytes);
5127 }
5128 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005129 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005130 *str = bytes2;
5131 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005132}
5133
5134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005135/* Primary internal function which creates utf8 encoded bytes objects.
5136
5137 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005138 and allocate exactly as much space needed at the end. Else allocate the
5139 maximum possible needed (4 result bytes per Unicode character), and return
5140 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005141*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005142PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005143_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005144{
Victor Stinner6099a032011-12-18 14:22:26 +01005145 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005146 void *data;
5147 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005149 if (!PyUnicode_Check(unicode)) {
5150 PyErr_BadArgument();
5151 return NULL;
5152 }
5153
5154 if (PyUnicode_READY(unicode) == -1)
5155 return NULL;
5156
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005157 if (PyUnicode_UTF8(unicode))
5158 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5159 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005160
5161 kind = PyUnicode_KIND(unicode);
5162 data = PyUnicode_DATA(unicode);
5163 size = PyUnicode_GET_LENGTH(unicode);
5164
Benjamin Petersonead6b532011-12-20 17:23:42 -06005165 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005166 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005167 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005168 case PyUnicode_1BYTE_KIND:
5169 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5170 assert(!PyUnicode_IS_ASCII(unicode));
5171 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5172 case PyUnicode_2BYTE_KIND:
5173 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5174 case PyUnicode_4BYTE_KIND:
5175 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005176 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005177}
5178
Alexander Belopolsky40018472011-02-26 01:02:56 +00005179PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005180PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5181 Py_ssize_t size,
5182 const char *errors)
5183{
5184 PyObject *v, *unicode;
5185
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005186 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005187 if (unicode == NULL)
5188 return NULL;
5189 v = _PyUnicode_AsUTF8String(unicode, errors);
5190 Py_DECREF(unicode);
5191 return v;
5192}
5193
5194PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005195PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005196{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005197 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005198}
5199
Walter Dörwald41980ca2007-08-16 21:55:45 +00005200/* --- UTF-32 Codec ------------------------------------------------------- */
5201
5202PyObject *
5203PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005204 Py_ssize_t size,
5205 const char *errors,
5206 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005207{
5208 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5209}
5210
5211PyObject *
5212PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005213 Py_ssize_t size,
5214 const char *errors,
5215 int *byteorder,
5216 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217{
5218 const char *starts = s;
5219 Py_ssize_t startinpos;
5220 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005221 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005222 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005223 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005224 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005225 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005226 PyObject *errorHandler = NULL;
5227 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005228
Walter Dörwald41980ca2007-08-16 21:55:45 +00005229 q = (unsigned char *)s;
5230 e = q + size;
5231
5232 if (byteorder)
5233 bo = *byteorder;
5234
5235 /* Check for BOM marks (U+FEFF) in the input and adjust current
5236 byte order setting accordingly. In native mode, the leading BOM
5237 mark is skipped, in all other modes, it is copied to the output
5238 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005239 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005240 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005241 if (bom == 0x0000FEFF) {
5242 bo = -1;
5243 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005244 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005245 else if (bom == 0xFFFE0000) {
5246 bo = 1;
5247 q += 4;
5248 }
5249 if (byteorder)
5250 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005251 }
5252
Victor Stinnere64322e2012-10-30 23:12:47 +01005253 if (q == e) {
5254 if (consumed)
5255 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005256 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257 }
5258
Victor Stinnere64322e2012-10-30 23:12:47 +01005259#ifdef WORDS_BIGENDIAN
5260 le = bo < 0;
5261#else
5262 le = bo <= 0;
5263#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005264 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005265
Victor Stinner8f674cc2013-04-17 23:02:17 +02005266 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005267 writer.min_length = (e - q + 3) / 4;
5268 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005269 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005270
Victor Stinnere64322e2012-10-30 23:12:47 +01005271 while (1) {
5272 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005273 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005274
Victor Stinnere64322e2012-10-30 23:12:47 +01005275 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005276 enum PyUnicode_Kind kind = writer.kind;
5277 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005278 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005279 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005280 if (le) {
5281 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005282 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005283 if (ch > maxch)
5284 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005285 if (kind != PyUnicode_1BYTE_KIND &&
5286 Py_UNICODE_IS_SURROGATE(ch))
5287 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005288 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005289 q += 4;
5290 } while (q <= last);
5291 }
5292 else {
5293 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005294 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005295 if (ch > maxch)
5296 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005297 if (kind != PyUnicode_1BYTE_KIND &&
5298 Py_UNICODE_IS_SURROGATE(ch))
5299 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005300 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005301 q += 4;
5302 } while (q <= last);
5303 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005304 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005305 }
5306
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005307 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005308 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005309 startinpos = ((const char *)q) - starts;
5310 endinpos = startinpos + 4;
5311 }
5312 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005313 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005314 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005315 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005316 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005317 startinpos = ((const char *)q) - starts;
5318 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005320 else {
5321 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005322 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005323 goto onError;
5324 q += 4;
5325 continue;
5326 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005327 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005328 startinpos = ((const char *)q) - starts;
5329 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005331
5332 /* The remaining input chars are ignored if the callback
5333 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005334 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005335 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005336 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005338 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005339 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005340 }
5341
Walter Dörwald41980ca2007-08-16 21:55:45 +00005342 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005343 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005344
Walter Dörwald41980ca2007-08-16 21:55:45 +00005345 Py_XDECREF(errorHandler);
5346 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005347 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005348
Benjamin Peterson29060642009-01-31 22:14:21 +00005349 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005350 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351 Py_XDECREF(errorHandler);
5352 Py_XDECREF(exc);
5353 return NULL;
5354}
5355
5356PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005357_PyUnicode_EncodeUTF32(PyObject *str,
5358 const char *errors,
5359 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005360{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005361 enum PyUnicode_Kind kind;
5362 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005363 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005364 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005365 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005366#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005367 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005368#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005369 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005370#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005371 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005372 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005373 PyObject *errorHandler = NULL;
5374 PyObject *exc = NULL;
5375 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005376
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005377 if (!PyUnicode_Check(str)) {
5378 PyErr_BadArgument();
5379 return NULL;
5380 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005381 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005382 return NULL;
5383 kind = PyUnicode_KIND(str);
5384 data = PyUnicode_DATA(str);
5385 len = PyUnicode_GET_LENGTH(str);
5386
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005387 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005388 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005389 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005390 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005391 if (v == NULL)
5392 return NULL;
5393
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005394 /* output buffer is 4-bytes aligned */
5395 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005396 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005397 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005398 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005399 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005400 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005401
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005402 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005403 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005404 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005405 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005406 else
5407 encoding = "utf-32";
5408
5409 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005410 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5411 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005412 }
5413
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005414 pos = 0;
5415 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005416 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005417
5418 if (kind == PyUnicode_2BYTE_KIND) {
5419 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5420 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005421 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005422 else {
5423 assert(kind == PyUnicode_4BYTE_KIND);
5424 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5425 &out, native_ordering);
5426 }
5427 if (pos == len)
5428 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005429
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005430 rep = unicode_encode_call_errorhandler(
5431 errors, &errorHandler,
5432 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005433 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005434 if (!rep)
5435 goto error;
5436
5437 if (PyBytes_Check(rep)) {
5438 repsize = PyBytes_GET_SIZE(rep);
5439 if (repsize & 3) {
5440 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005441 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005442 "surrogates not allowed");
5443 goto error;
5444 }
5445 moreunits = repsize / 4;
5446 }
5447 else {
5448 assert(PyUnicode_Check(rep));
5449 if (PyUnicode_READY(rep) < 0)
5450 goto error;
5451 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5452 if (!PyUnicode_IS_ASCII(rep)) {
5453 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005454 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005455 "surrogates not allowed");
5456 goto error;
5457 }
5458 }
5459
5460 /* four bytes are reserved for each surrogate */
5461 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005462 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005463 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005464 /* integer overflow */
5465 PyErr_NoMemory();
5466 goto error;
5467 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005468 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005470 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005471 }
5472
5473 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005474 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005475 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005476 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005477 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005478 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5479 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005480 }
5481
5482 Py_CLEAR(rep);
5483 }
5484
5485 /* Cut back to size actually needed. This is necessary for, for example,
5486 encoding of a string containing isolated surrogates and the 'ignore'
5487 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005488 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005489 if (nsize != PyBytes_GET_SIZE(v))
5490 _PyBytes_Resize(&v, nsize);
5491 Py_XDECREF(errorHandler);
5492 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005493 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005494 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005495 error:
5496 Py_XDECREF(rep);
5497 Py_XDECREF(errorHandler);
5498 Py_XDECREF(exc);
5499 Py_XDECREF(v);
5500 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005501}
5502
Alexander Belopolsky40018472011-02-26 01:02:56 +00005503PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005504PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5505 Py_ssize_t size,
5506 const char *errors,
5507 int byteorder)
5508{
5509 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005510 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005511 if (tmp == NULL)
5512 return NULL;
5513 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5514 Py_DECREF(tmp);
5515 return result;
5516}
5517
5518PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005519PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005520{
Victor Stinnerb960b342011-11-20 19:12:52 +01005521 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005522}
5523
Guido van Rossumd57fd912000-03-10 22:53:23 +00005524/* --- UTF-16 Codec ------------------------------------------------------- */
5525
Tim Peters772747b2001-08-09 22:21:55 +00005526PyObject *
5527PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005528 Py_ssize_t size,
5529 const char *errors,
5530 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005531{
Walter Dörwald69652032004-09-07 20:24:22 +00005532 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5533}
5534
5535PyObject *
5536PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005537 Py_ssize_t size,
5538 const char *errors,
5539 int *byteorder,
5540 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005541{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005542 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005543 Py_ssize_t startinpos;
5544 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005545 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005546 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005547 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005548 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005549 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005550 PyObject *errorHandler = NULL;
5551 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005552 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005553
Tim Peters772747b2001-08-09 22:21:55 +00005554 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005555 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556
5557 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005558 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005560 /* Check for BOM marks (U+FEFF) in the input and adjust current
5561 byte order setting accordingly. In native mode, the leading BOM
5562 mark is skipped, in all other modes, it is copied to the output
5563 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005564 if (bo == 0 && size >= 2) {
5565 const Py_UCS4 bom = (q[1] << 8) | q[0];
5566 if (bom == 0xFEFF) {
5567 q += 2;
5568 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005569 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005570 else if (bom == 0xFFFE) {
5571 q += 2;
5572 bo = 1;
5573 }
5574 if (byteorder)
5575 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005576 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005577
Antoine Pitrou63065d72012-05-15 23:48:04 +02005578 if (q == e) {
5579 if (consumed)
5580 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005581 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005582 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005583
Christian Heimes743e0cd2012-10-17 23:52:17 +02005584#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005585 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005586 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005587#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005588 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005589 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005590#endif
Tim Peters772747b2001-08-09 22:21:55 +00005591
Antoine Pitrou63065d72012-05-15 23:48:04 +02005592 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005593 character count normally. Error handler will take care of
5594 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005595 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005596 writer.min_length = (e - q + 1) / 2;
5597 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005598 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599
Antoine Pitrou63065d72012-05-15 23:48:04 +02005600 while (1) {
5601 Py_UCS4 ch = 0;
5602 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005603 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005604 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005605 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005606 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005607 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005608 native_ordering);
5609 else
5610 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005611 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005612 native_ordering);
5613 } else if (kind == PyUnicode_2BYTE_KIND) {
5614 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005615 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005616 native_ordering);
5617 } else {
5618 assert(kind == PyUnicode_4BYTE_KIND);
5619 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005620 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005621 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005622 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005623 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005624
Antoine Pitrou63065d72012-05-15 23:48:04 +02005625 switch (ch)
5626 {
5627 case 0:
5628 /* remaining byte at the end? (size should be even) */
5629 if (q == e || consumed)
5630 goto End;
5631 errmsg = "truncated data";
5632 startinpos = ((const char *)q) - starts;
5633 endinpos = ((const char *)e) - starts;
5634 break;
5635 /* The remaining input chars are ignored if the callback
5636 chooses to skip the input */
5637 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005638 q -= 2;
5639 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005640 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005641 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005642 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005643 endinpos = ((const char *)e) - starts;
5644 break;
5645 case 2:
5646 errmsg = "illegal encoding";
5647 startinpos = ((const char *)q) - 2 - starts;
5648 endinpos = startinpos + 2;
5649 break;
5650 case 3:
5651 errmsg = "illegal UTF-16 surrogate";
5652 startinpos = ((const char *)q) - 4 - starts;
5653 endinpos = startinpos + 2;
5654 break;
5655 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005656 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005657 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005658 continue;
5659 }
5660
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005661 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005662 errors,
5663 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005664 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005665 &starts,
5666 (const char **)&e,
5667 &startinpos,
5668 &endinpos,
5669 &exc,
5670 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005671 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673 }
5674
Antoine Pitrou63065d72012-05-15 23:48:04 +02005675End:
Walter Dörwald69652032004-09-07 20:24:22 +00005676 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005677 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005678
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005679 Py_XDECREF(errorHandler);
5680 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005681 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005684 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005685 Py_XDECREF(errorHandler);
5686 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687 return NULL;
5688}
5689
Tim Peters772747b2001-08-09 22:21:55 +00005690PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005691_PyUnicode_EncodeUTF16(PyObject *str,
5692 const char *errors,
5693 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005695 enum PyUnicode_Kind kind;
5696 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005697 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005698 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005699 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005700 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005701#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005702 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005703#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005704 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005705#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005706 const char *encoding;
5707 Py_ssize_t nsize, pos;
5708 PyObject *errorHandler = NULL;
5709 PyObject *exc = NULL;
5710 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005711
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005712 if (!PyUnicode_Check(str)) {
5713 PyErr_BadArgument();
5714 return NULL;
5715 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005716 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005717 return NULL;
5718 kind = PyUnicode_KIND(str);
5719 data = PyUnicode_DATA(str);
5720 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005721
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005722 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005723 if (kind == PyUnicode_4BYTE_KIND) {
5724 const Py_UCS4 *in = (const Py_UCS4 *)data;
5725 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005726 while (in < end) {
5727 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005728 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005729 }
5730 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005731 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005732 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005734 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005735 nsize = len + pairs + (byteorder == 0);
5736 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005737 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005739 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005741 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005742 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005743 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005744 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005745 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005746 }
5747 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005748 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005749 }
Tim Peters772747b2001-08-09 22:21:55 +00005750
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005751 if (kind == PyUnicode_1BYTE_KIND) {
5752 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5753 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005754 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005755
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005756 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005757 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005758 }
5759 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005760 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005761 }
5762 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005763 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005764 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005765
5766 pos = 0;
5767 while (pos < len) {
5768 Py_ssize_t repsize, moreunits;
5769
5770 if (kind == PyUnicode_2BYTE_KIND) {
5771 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5772 &out, native_ordering);
5773 }
5774 else {
5775 assert(kind == PyUnicode_4BYTE_KIND);
5776 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5777 &out, native_ordering);
5778 }
5779 if (pos == len)
5780 break;
5781
5782 rep = unicode_encode_call_errorhandler(
5783 errors, &errorHandler,
5784 encoding, "surrogates not allowed",
5785 str, &exc, pos, pos + 1, &pos);
5786 if (!rep)
5787 goto error;
5788
5789 if (PyBytes_Check(rep)) {
5790 repsize = PyBytes_GET_SIZE(rep);
5791 if (repsize & 1) {
5792 raise_encode_exception(&exc, encoding,
5793 str, pos - 1, pos,
5794 "surrogates not allowed");
5795 goto error;
5796 }
5797 moreunits = repsize / 2;
5798 }
5799 else {
5800 assert(PyUnicode_Check(rep));
5801 if (PyUnicode_READY(rep) < 0)
5802 goto error;
5803 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5804 if (!PyUnicode_IS_ASCII(rep)) {
5805 raise_encode_exception(&exc, encoding,
5806 str, pos - 1, pos,
5807 "surrogates not allowed");
5808 goto error;
5809 }
5810 }
5811
5812 /* two bytes are reserved for each surrogate */
5813 if (moreunits > 1) {
5814 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005815 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005816 /* integer overflow */
5817 PyErr_NoMemory();
5818 goto error;
5819 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005820 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005821 goto error;
5822 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5823 }
5824
5825 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005826 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005827 out += moreunits;
5828 } else /* rep is unicode */ {
5829 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5830 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5831 &out, native_ordering);
5832 }
5833
5834 Py_CLEAR(rep);
5835 }
5836
5837 /* Cut back to size actually needed. This is necessary for, for example,
5838 encoding of a string containing isolated surrogates and the 'ignore' handler
5839 is used. */
5840 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5841 if (nsize != PyBytes_GET_SIZE(v))
5842 _PyBytes_Resize(&v, nsize);
5843 Py_XDECREF(errorHandler);
5844 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005845 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005846 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005847 error:
5848 Py_XDECREF(rep);
5849 Py_XDECREF(errorHandler);
5850 Py_XDECREF(exc);
5851 Py_XDECREF(v);
5852 return NULL;
5853#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005854}
5855
Alexander Belopolsky40018472011-02-26 01:02:56 +00005856PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005857PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5858 Py_ssize_t size,
5859 const char *errors,
5860 int byteorder)
5861{
5862 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005863 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005864 if (tmp == NULL)
5865 return NULL;
5866 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5867 Py_DECREF(tmp);
5868 return result;
5869}
5870
5871PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005872PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005873{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005874 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875}
5876
5877/* --- Unicode Escape Codec ----------------------------------------------- */
5878
Fredrik Lundh06d12682001-01-24 07:59:11 +00005879static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005880
Alexander Belopolsky40018472011-02-26 01:02:56 +00005881PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005882_PyUnicode_DecodeUnicodeEscape(const char *s,
5883 Py_ssize_t size,
5884 const char *errors,
5885 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005887 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005888 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005890 PyObject *errorHandler = NULL;
5891 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005892
Eric V. Smith42454af2016-10-31 09:22:08 -04005893 // so we can remember if we've seen an invalid escape char or not
5894 *first_invalid_escape = NULL;
5895
Victor Stinner62ec3312016-09-06 17:04:34 -07005896 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005897 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005898 }
5899 /* Escaped strings will always be longer than the resulting
5900 Unicode string, so we start with size here and then reduce the
5901 length after conversion to the true value.
5902 (but if the error callback returns a long replacement string
5903 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005904 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005905 writer.min_length = size;
5906 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5907 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005908 }
5909
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 end = s + size;
5911 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005912 unsigned char c = (unsigned char) *s++;
5913 Py_UCS4 ch;
5914 int count;
5915 Py_ssize_t startinpos;
5916 Py_ssize_t endinpos;
5917 const char *message;
5918
5919#define WRITE_ASCII_CHAR(ch) \
5920 do { \
5921 assert(ch <= 127); \
5922 assert(writer.pos < writer.size); \
5923 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5924 } while(0)
5925
5926#define WRITE_CHAR(ch) \
5927 do { \
5928 if (ch <= writer.maxchar) { \
5929 assert(writer.pos < writer.size); \
5930 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5931 } \
5932 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5933 goto onError; \
5934 } \
5935 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005936
5937 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005938 if (c != '\\') {
5939 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005940 continue;
5941 }
5942
Victor Stinner62ec3312016-09-06 17:04:34 -07005943 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005944 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005945 if (s >= end) {
5946 message = "\\ at end of string";
5947 goto error;
5948 }
5949 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005950
Victor Stinner62ec3312016-09-06 17:04:34 -07005951 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005952 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005953
Benjamin Peterson29060642009-01-31 22:14:21 +00005954 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005955 case '\n': continue;
5956 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5957 case '\'': WRITE_ASCII_CHAR('\''); continue;
5958 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5959 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005960 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005961 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5962 case 't': WRITE_ASCII_CHAR('\t'); continue;
5963 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5964 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005965 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005966 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005967 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005968 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969
Benjamin Peterson29060642009-01-31 22:14:21 +00005970 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971 case '0': case '1': case '2': case '3':
5972 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005973 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005974 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005975 ch = (ch<<3) + *s++ - '0';
5976 if (s < end && '0' <= *s && *s <= '7') {
5977 ch = (ch<<3) + *s++ - '0';
5978 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005980 WRITE_CHAR(ch);
5981 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982
Benjamin Peterson29060642009-01-31 22:14:21 +00005983 /* hex escapes */
5984 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005986 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005987 message = "truncated \\xXX escape";
5988 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005992 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005993 message = "truncated \\uXXXX escape";
5994 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995
Benjamin Peterson29060642009-01-31 22:14:21 +00005996 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005997 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005998 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005999 message = "truncated \\UXXXXXXXX escape";
6000 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006002 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006003 ch <<= 4;
6004 if (c >= '0' && c <= '9') {
6005 ch += c - '0';
6006 }
6007 else if (c >= 'a' && c <= 'f') {
6008 ch += c - ('a' - 10);
6009 }
6010 else if (c >= 'A' && c <= 'F') {
6011 ch += c - ('A' - 10);
6012 }
6013 else {
6014 break;
6015 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006016 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006017 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006018 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006019 }
6020
6021 /* when we get here, ch is a 32-bit unicode character */
6022 if (ch > MAX_UNICODE) {
6023 message = "illegal Unicode character";
6024 goto error;
6025 }
6026
6027 WRITE_CHAR(ch);
6028 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006029
Benjamin Peterson29060642009-01-31 22:14:21 +00006030 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006031 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006032 if (ucnhash_CAPI == NULL) {
6033 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006034 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6035 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006036 if (ucnhash_CAPI == NULL) {
6037 PyErr_SetString(
6038 PyExc_UnicodeError,
6039 "\\N escapes not supported (can't load unicodedata module)"
6040 );
6041 goto onError;
6042 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006043 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006044
6045 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006046 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006047 const char *start = ++s;
6048 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006049 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006050 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006051 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006052 namelen = s - start;
6053 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006055 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006056 ch = 0xffffffff; /* in case 'getcode' messes up */
6057 if (namelen <= INT_MAX &&
6058 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6059 &ch, 0)) {
6060 assert(ch <= MAX_UNICODE);
6061 WRITE_CHAR(ch);
6062 continue;
6063 }
6064 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006065 }
6066 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006067 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006068
6069 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006070 if (*first_invalid_escape == NULL) {
6071 *first_invalid_escape = s-1; /* Back up one char, since we've
6072 already incremented s. */
6073 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006074 WRITE_ASCII_CHAR('\\');
6075 WRITE_CHAR(c);
6076 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006078
6079 error:
6080 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006081 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006082 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006083 errors, &errorHandler,
6084 "unicodeescape", message,
6085 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006086 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006087 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006088 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006089 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006090
6091#undef WRITE_ASCII_CHAR
6092#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006094
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006095 Py_XDECREF(errorHandler);
6096 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006097 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006098
Benjamin Peterson29060642009-01-31 22:14:21 +00006099 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006100 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006101 Py_XDECREF(errorHandler);
6102 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006103 return NULL;
6104}
6105
Eric V. Smith42454af2016-10-31 09:22:08 -04006106PyObject *
6107PyUnicode_DecodeUnicodeEscape(const char *s,
6108 Py_ssize_t size,
6109 const char *errors)
6110{
6111 const char *first_invalid_escape;
6112 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6113 &first_invalid_escape);
6114 if (result == NULL)
6115 return NULL;
6116 if (first_invalid_escape != NULL) {
6117 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6118 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006119 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006120 Py_DECREF(result);
6121 return NULL;
6122 }
6123 }
6124 return result;
6125}
6126
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006127/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006128
Alexander Belopolsky40018472011-02-26 01:02:56 +00006129PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006130PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006132 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006133 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006134 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006135 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006136 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006137 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138
Ezio Melottie7f90372012-10-05 03:33:31 +03006139 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006140 escape.
6141
Ezio Melottie7f90372012-10-05 03:33:31 +03006142 For UCS1 strings it's '\xxx', 4 bytes per source character.
6143 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6144 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006145 */
6146
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006147 if (!PyUnicode_Check(unicode)) {
6148 PyErr_BadArgument();
6149 return NULL;
6150 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006151 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006152 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006153 }
Victor Stinner358af132015-10-12 22:36:57 +02006154
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006155 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006156 if (len == 0) {
6157 return PyBytes_FromStringAndSize(NULL, 0);
6158 }
6159
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160 kind = PyUnicode_KIND(unicode);
6161 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006162 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6163 bytes, and 1 byte characters 4. */
6164 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006165 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006166 return PyErr_NoMemory();
6167 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006168 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006169 if (repr == NULL) {
6170 return NULL;
6171 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006172
Victor Stinner62ec3312016-09-06 17:04:34 -07006173 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006174 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006175 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006176
Victor Stinner62ec3312016-09-06 17:04:34 -07006177 /* U+0000-U+00ff range */
6178 if (ch < 0x100) {
6179 if (ch >= ' ' && ch < 127) {
6180 if (ch != '\\') {
6181 /* Copy printable US ASCII as-is */
6182 *p++ = (char) ch;
6183 }
6184 /* Escape backslashes */
6185 else {
6186 *p++ = '\\';
6187 *p++ = '\\';
6188 }
6189 }
Victor Stinner358af132015-10-12 22:36:57 +02006190
Victor Stinner62ec3312016-09-06 17:04:34 -07006191 /* Map special whitespace to '\t', \n', '\r' */
6192 else if (ch == '\t') {
6193 *p++ = '\\';
6194 *p++ = 't';
6195 }
6196 else if (ch == '\n') {
6197 *p++ = '\\';
6198 *p++ = 'n';
6199 }
6200 else if (ch == '\r') {
6201 *p++ = '\\';
6202 *p++ = 'r';
6203 }
6204
6205 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6206 else {
6207 *p++ = '\\';
6208 *p++ = 'x';
6209 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6210 *p++ = Py_hexdigits[ch & 0x000F];
6211 }
Tim Petersced69f82003-09-16 20:30:58 +00006212 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006213 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006214 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215 *p++ = '\\';
6216 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006217 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6218 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6219 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6220 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006222 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6223 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006224
Victor Stinner62ec3312016-09-06 17:04:34 -07006225 /* Make sure that the first two digits are zero */
6226 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006227 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006228 *p++ = 'U';
6229 *p++ = '0';
6230 *p++ = '0';
6231 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6232 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6233 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6234 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6235 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6236 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006237 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239
Victor Stinner62ec3312016-09-06 17:04:34 -07006240 assert(p - PyBytes_AS_STRING(repr) > 0);
6241 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6242 return NULL;
6243 }
6244 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245}
6246
Alexander Belopolsky40018472011-02-26 01:02:56 +00006247PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006248PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6249 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006250{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006251 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006252 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006253 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006255 }
6256
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006257 result = PyUnicode_AsUnicodeEscapeString(tmp);
6258 Py_DECREF(tmp);
6259 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006260}
6261
6262/* --- Raw Unicode Escape Codec ------------------------------------------- */
6263
Alexander Belopolsky40018472011-02-26 01:02:56 +00006264PyObject *
6265PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006266 Py_ssize_t size,
6267 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006268{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006269 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006270 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006271 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006272 PyObject *errorHandler = NULL;
6273 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006274
Victor Stinner62ec3312016-09-06 17:04:34 -07006275 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006276 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006277 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006278
Guido van Rossumd57fd912000-03-10 22:53:23 +00006279 /* Escaped strings will always be longer than the resulting
6280 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006281 length after conversion to the true value. (But decoding error
6282 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006283 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006284 writer.min_length = size;
6285 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6286 goto onError;
6287 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006288
Guido van Rossumd57fd912000-03-10 22:53:23 +00006289 end = s + size;
6290 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006291 unsigned char c = (unsigned char) *s++;
6292 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006293 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006294 Py_ssize_t startinpos;
6295 Py_ssize_t endinpos;
6296 const char *message;
6297
6298#define WRITE_CHAR(ch) \
6299 do { \
6300 if (ch <= writer.maxchar) { \
6301 assert(writer.pos < writer.size); \
6302 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6303 } \
6304 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6305 goto onError; \
6306 } \
6307 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308
Benjamin Peterson29060642009-01-31 22:14:21 +00006309 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006310 if (c != '\\' || s >= end) {
6311 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006312 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006313 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006314
Victor Stinner62ec3312016-09-06 17:04:34 -07006315 c = (unsigned char) *s++;
6316 if (c == 'u') {
6317 count = 4;
6318 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006319 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006320 else if (c == 'U') {
6321 count = 8;
6322 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006323 }
6324 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006325 assert(writer.pos < writer.size);
6326 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6327 WRITE_CHAR(c);
6328 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006329 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006330 startinpos = s - starts - 2;
6331
6332 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6333 for (ch = 0; count && s < end; ++s, --count) {
6334 c = (unsigned char)*s;
6335 ch <<= 4;
6336 if (c >= '0' && c <= '9') {
6337 ch += c - '0';
6338 }
6339 else if (c >= 'a' && c <= 'f') {
6340 ch += c - ('a' - 10);
6341 }
6342 else if (c >= 'A' && c <= 'F') {
6343 ch += c - ('A' - 10);
6344 }
6345 else {
6346 break;
6347 }
6348 }
6349 if (!count) {
6350 if (ch <= MAX_UNICODE) {
6351 WRITE_CHAR(ch);
6352 continue;
6353 }
6354 message = "\\Uxxxxxxxx out of range";
6355 }
6356
6357 endinpos = s-starts;
6358 writer.min_length = end - s + writer.pos;
6359 if (unicode_decode_call_errorhandler_writer(
6360 errors, &errorHandler,
6361 "rawunicodeescape", message,
6362 &starts, &end, &startinpos, &endinpos, &exc, &s,
6363 &writer)) {
6364 goto onError;
6365 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006366 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006367
6368#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006369 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006370 Py_XDECREF(errorHandler);
6371 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006372 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006373
Benjamin Peterson29060642009-01-31 22:14:21 +00006374 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006375 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006376 Py_XDECREF(errorHandler);
6377 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006378 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006379
Guido van Rossumd57fd912000-03-10 22:53:23 +00006380}
6381
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006382
Alexander Belopolsky40018472011-02-26 01:02:56 +00006383PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006384PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006385{
Victor Stinner62ec3312016-09-06 17:04:34 -07006386 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006387 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006388 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006389 int kind;
6390 void *data;
6391 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006392
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006393 if (!PyUnicode_Check(unicode)) {
6394 PyErr_BadArgument();
6395 return NULL;
6396 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006397 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006398 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006399 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006400 kind = PyUnicode_KIND(unicode);
6401 data = PyUnicode_DATA(unicode);
6402 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006403 if (kind == PyUnicode_1BYTE_KIND) {
6404 return PyBytes_FromStringAndSize(data, len);
6405 }
Victor Stinner0e368262011-11-10 20:12:49 +01006406
Victor Stinner62ec3312016-09-06 17:04:34 -07006407 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6408 bytes, and 1 byte characters 4. */
6409 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006410
Victor Stinner62ec3312016-09-06 17:04:34 -07006411 if (len > PY_SSIZE_T_MAX / expandsize) {
6412 return PyErr_NoMemory();
6413 }
6414 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6415 if (repr == NULL) {
6416 return NULL;
6417 }
6418 if (len == 0) {
6419 return repr;
6420 }
6421
6422 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006423 for (pos = 0; pos < len; pos++) {
6424 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006425
Victor Stinner62ec3312016-09-06 17:04:34 -07006426 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6427 if (ch < 0x100) {
6428 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006429 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006430 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006431 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006432 *p++ = '\\';
6433 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006434 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6435 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6436 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6437 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006438 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006439 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6440 else {
6441 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6442 *p++ = '\\';
6443 *p++ = 'U';
6444 *p++ = '0';
6445 *p++ = '0';
6446 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6447 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6448 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6449 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6450 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6451 *p++ = Py_hexdigits[ch & 15];
6452 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006453 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006454
Victor Stinner62ec3312016-09-06 17:04:34 -07006455 assert(p > PyBytes_AS_STRING(repr));
6456 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6457 return NULL;
6458 }
6459 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006460}
6461
Alexander Belopolsky40018472011-02-26 01:02:56 +00006462PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006463PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6464 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006465{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006466 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006467 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006468 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006469 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006470 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6471 Py_DECREF(tmp);
6472 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006473}
6474
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006475/* --- Unicode Internal Codec ------------------------------------------- */
6476
Alexander Belopolsky40018472011-02-26 01:02:56 +00006477PyObject *
6478_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006479 Py_ssize_t size,
6480 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006481{
6482 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006483 Py_ssize_t startinpos;
6484 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006485 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006486 const char *end;
6487 const char *reason;
6488 PyObject *errorHandler = NULL;
6489 PyObject *exc = NULL;
6490
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006491 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006492 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006493 1))
6494 return NULL;
6495
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006496 if (size < 0) {
6497 PyErr_BadInternalCall();
6498 return NULL;
6499 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006500 if (size == 0)
6501 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006502
Victor Stinner8f674cc2013-04-17 23:02:17 +02006503 _PyUnicodeWriter_Init(&writer);
6504 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6505 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006507 }
6508 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006509
Victor Stinner8f674cc2013-04-17 23:02:17 +02006510 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006511 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006512 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006513 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006514 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006515 endinpos = end-starts;
6516 reason = "truncated input";
6517 goto error;
6518 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006519 /* We copy the raw representation one byte at a time because the
6520 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006521 ((char *) &uch)[0] = s[0];
6522 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006523#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006524 ((char *) &uch)[2] = s[2];
6525 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006526#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006527 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006528#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006529 /* We have to sanity check the raw data, otherwise doom looms for
6530 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006531 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006532 endinpos = s - starts + Py_UNICODE_SIZE;
6533 reason = "illegal code point (> 0x10FFFF)";
6534 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006535 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006536#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006537 s += Py_UNICODE_SIZE;
6538#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006539 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006540 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006541 Py_UNICODE uch2;
6542 ((char *) &uch2)[0] = s[0];
6543 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006544 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006545 {
Victor Stinner551ac952011-11-29 22:58:13 +01006546 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006547 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006548 }
6549 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006550#endif
6551
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006552 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006553 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006554 continue;
6555
6556 error:
6557 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006558 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006559 errors, &errorHandler,
6560 "unicode_internal", reason,
6561 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006562 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006563 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006564 }
6565
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006566 Py_XDECREF(errorHandler);
6567 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006568 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006569
Benjamin Peterson29060642009-01-31 22:14:21 +00006570 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006571 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006572 Py_XDECREF(errorHandler);
6573 Py_XDECREF(exc);
6574 return NULL;
6575}
6576
Guido van Rossumd57fd912000-03-10 22:53:23 +00006577/* --- Latin-1 Codec ------------------------------------------------------ */
6578
Alexander Belopolsky40018472011-02-26 01:02:56 +00006579PyObject *
6580PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006581 Py_ssize_t size,
6582 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006583{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006584 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006585 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006586}
6587
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006588/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006589static void
6590make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006591 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006592 PyObject *unicode,
6593 Py_ssize_t startpos, Py_ssize_t endpos,
6594 const char *reason)
6595{
6596 if (*exceptionObject == NULL) {
6597 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006598 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006599 encoding, unicode, startpos, endpos, reason);
6600 }
6601 else {
6602 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6603 goto onError;
6604 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6605 goto onError;
6606 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6607 goto onError;
6608 return;
6609 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006610 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006611 }
6612}
6613
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006614/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006615static void
6616raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006617 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006618 PyObject *unicode,
6619 Py_ssize_t startpos, Py_ssize_t endpos,
6620 const char *reason)
6621{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006622 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006623 encoding, unicode, startpos, endpos, reason);
6624 if (*exceptionObject != NULL)
6625 PyCodec_StrictErrors(*exceptionObject);
6626}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006627
6628/* error handling callback helper:
6629 build arguments, call the callback and check the arguments,
6630 put the result into newpos and return the replacement string, which
6631 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006632static PyObject *
6633unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006634 PyObject **errorHandler,
6635 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006637 Py_ssize_t startpos, Py_ssize_t endpos,
6638 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006639{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006640 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006641 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 PyObject *restuple;
6643 PyObject *resunicode;
6644
6645 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006646 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649 }
6650
Benjamin Petersonbac79492012-01-14 13:34:47 -05006651 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006652 return NULL;
6653 len = PyUnicode_GET_LENGTH(unicode);
6654
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006655 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006656 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006657 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006658 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006660 restuple = PyObject_CallFunctionObjArgs(
6661 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006662 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006663 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006664 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006665 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 Py_DECREF(restuple);
6667 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006669 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006670 &resunicode, newpos)) {
6671 Py_DECREF(restuple);
6672 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006674 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6675 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6676 Py_DECREF(restuple);
6677 return NULL;
6678 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006679 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006680 *newpos = len + *newpos;
6681 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006682 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006683 Py_DECREF(restuple);
6684 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006685 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686 Py_INCREF(resunicode);
6687 Py_DECREF(restuple);
6688 return resunicode;
6689}
6690
Alexander Belopolsky40018472011-02-26 01:02:56 +00006691static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006692unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006693 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006694 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006696 /* input state */
6697 Py_ssize_t pos=0, size;
6698 int kind;
6699 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006700 /* pointer into the output */
6701 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006702 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6703 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006704 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006705 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006706 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006707 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006708 /* output object */
6709 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006710
Benjamin Petersonbac79492012-01-14 13:34:47 -05006711 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006712 return NULL;
6713 size = PyUnicode_GET_LENGTH(unicode);
6714 kind = PyUnicode_KIND(unicode);
6715 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716 /* allocate enough for a simple encoding without
6717 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006718 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006719 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006720
6721 _PyBytesWriter_Init(&writer);
6722 str = _PyBytesWriter_Alloc(&writer, size);
6723 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006724 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006725
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006726 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006727 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006728
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006730 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006732 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006733 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006734 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006736 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006737 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006738 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006739 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006741
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006742 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006744
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006745 /* Only overallocate the buffer if it's not the last write */
6746 writer.overallocate = (collend < size);
6747
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006749 if (error_handler == _Py_ERROR_UNKNOWN)
6750 error_handler = get_error_handler(errors);
6751
6752 switch (error_handler) {
6753 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006754 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006756
6757 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006758 memset(str, '?', collend - collstart);
6759 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006760 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006761 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006762 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006763 break;
Victor Stinner50149202015-09-22 00:26:54 +02006764
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006765 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006766 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006767 writer.min_size -= (collend - collstart);
6768 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006769 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006770 if (str == NULL)
6771 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006772 pos = collend;
6773 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006774
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006775 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006776 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006777 writer.min_size -= (collend - collstart);
6778 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006779 unicode, collstart, collend);
6780 if (str == NULL)
6781 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006782 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006783 break;
Victor Stinner50149202015-09-22 00:26:54 +02006784
Victor Stinnerc3713e92015-09-29 12:32:13 +02006785 case _Py_ERROR_SURROGATEESCAPE:
6786 for (i = collstart; i < collend; ++i) {
6787 ch = PyUnicode_READ(kind, data, i);
6788 if (ch < 0xdc80 || 0xdcff < ch) {
6789 /* Not a UTF-8b surrogate */
6790 break;
6791 }
6792 *str++ = (char)(ch - 0xdc00);
6793 ++pos;
6794 }
6795 if (i >= collend)
6796 break;
6797 collstart = pos;
6798 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006799 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006800
Benjamin Peterson29060642009-01-31 22:14:21 +00006801 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006802 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6803 encoding, reason, unicode, &exc,
6804 collstart, collend, &newpos);
6805 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006806 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006807
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006808 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006809 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006810
Victor Stinner6bd525b2015-10-09 13:10:05 +02006811 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006812 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006813 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006814 PyBytes_AS_STRING(rep),
6815 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006816 if (str == NULL)
6817 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006818 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006819 else {
6820 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006821
Victor Stinner6bd525b2015-10-09 13:10:05 +02006822 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006823 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006824
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006825 if (limit == 256 ?
6826 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6827 !PyUnicode_IS_ASCII(rep))
6828 {
6829 /* Not all characters are smaller than limit */
6830 raise_encode_exception(&exc, encoding, unicode,
6831 collstart, collend, reason);
6832 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006833 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006834 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6835 str = _PyBytesWriter_WriteBytes(&writer, str,
6836 PyUnicode_DATA(rep),
6837 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006838 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006839 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006840 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006841 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006842
6843 /* If overallocation was disabled, ensure that it was the last
6844 write. Otherwise, we missed an optimization */
6845 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006846 }
6847 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006848
Victor Stinner50149202015-09-22 00:26:54 +02006849 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006850 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006851 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006852
6853 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006854 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006855 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006856 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006857 Py_XDECREF(exc);
6858 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006859}
6860
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006861/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006862PyObject *
6863PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006864 Py_ssize_t size,
6865 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006866{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006867 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006868 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006869 if (unicode == NULL)
6870 return NULL;
6871 result = unicode_encode_ucs1(unicode, errors, 256);
6872 Py_DECREF(unicode);
6873 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006874}
6875
Alexander Belopolsky40018472011-02-26 01:02:56 +00006876PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006877_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006878{
6879 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006880 PyErr_BadArgument();
6881 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006883 if (PyUnicode_READY(unicode) == -1)
6884 return NULL;
6885 /* Fast path: if it is a one-byte string, construct
6886 bytes object directly. */
6887 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6888 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6889 PyUnicode_GET_LENGTH(unicode));
6890 /* Non-Latin-1 characters present. Defer to above function to
6891 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006892 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006893}
6894
6895PyObject*
6896PyUnicode_AsLatin1String(PyObject *unicode)
6897{
6898 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006899}
6900
6901/* --- 7-bit ASCII Codec -------------------------------------------------- */
6902
Alexander Belopolsky40018472011-02-26 01:02:56 +00006903PyObject *
6904PyUnicode_DecodeASCII(const char *s,
6905 Py_ssize_t size,
6906 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006907{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006908 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006909 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006910 int kind;
6911 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006912 Py_ssize_t startinpos;
6913 Py_ssize_t endinpos;
6914 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006915 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006916 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006917 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006918 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006919
Guido van Rossumd57fd912000-03-10 22:53:23 +00006920 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006921 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006922
Guido van Rossumd57fd912000-03-10 22:53:23 +00006923 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006924 if (size == 1 && (unsigned char)s[0] < 128)
6925 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006926
Victor Stinner8f674cc2013-04-17 23:02:17 +02006927 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006928 writer.min_length = size;
6929 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006930 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006931
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006932 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006933 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006934 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006935 writer.pos = outpos;
6936 if (writer.pos == size)
6937 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006938
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006939 s += writer.pos;
6940 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006941 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006942 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006944 PyUnicode_WRITE(kind, data, writer.pos, c);
6945 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006946 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006947 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006948 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006949
6950 /* byte outsize range 0x00..0x7f: call the error handler */
6951
6952 if (error_handler == _Py_ERROR_UNKNOWN)
6953 error_handler = get_error_handler(errors);
6954
6955 switch (error_handler)
6956 {
6957 case _Py_ERROR_REPLACE:
6958 case _Py_ERROR_SURROGATEESCAPE:
6959 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006960 but we may switch to UCS2 at the first write */
6961 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6962 goto onError;
6963 kind = writer.kind;
6964 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006965
6966 if (error_handler == _Py_ERROR_REPLACE)
6967 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6968 else
6969 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6970 writer.pos++;
6971 ++s;
6972 break;
6973
6974 case _Py_ERROR_IGNORE:
6975 ++s;
6976 break;
6977
6978 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 startinpos = s-starts;
6980 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006981 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006982 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006983 "ascii", "ordinal not in range(128)",
6984 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006985 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006986 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006987 kind = writer.kind;
6988 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006989 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006990 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006991 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006992 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006993 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006994
Benjamin Peterson29060642009-01-31 22:14:21 +00006995 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006996 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006997 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006998 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006999 return NULL;
7000}
7001
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007002/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007003PyObject *
7004PyUnicode_EncodeASCII(const Py_UNICODE *p,
7005 Py_ssize_t size,
7006 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007007{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007008 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007009 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007010 if (unicode == NULL)
7011 return NULL;
7012 result = unicode_encode_ucs1(unicode, errors, 128);
7013 Py_DECREF(unicode);
7014 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007015}
7016
Alexander Belopolsky40018472011-02-26 01:02:56 +00007017PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007018_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007019{
7020 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007021 PyErr_BadArgument();
7022 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007023 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007024 if (PyUnicode_READY(unicode) == -1)
7025 return NULL;
7026 /* Fast path: if it is an ASCII-only string, construct bytes object
7027 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007028 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007029 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7030 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007031 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007032}
7033
7034PyObject *
7035PyUnicode_AsASCIIString(PyObject *unicode)
7036{
7037 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007038}
7039
Steve Dowercc16be82016-09-08 10:35:16 -07007040#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007041
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007042/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007043
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007044#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045#define NEED_RETRY
7046#endif
7047
Victor Stinner3a50e702011-10-18 21:21:00 +02007048#ifndef WC_ERR_INVALID_CHARS
7049# define WC_ERR_INVALID_CHARS 0x0080
7050#endif
7051
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007052static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007053code_page_name(UINT code_page, PyObject **obj)
7054{
7055 *obj = NULL;
7056 if (code_page == CP_ACP)
7057 return "mbcs";
7058 if (code_page == CP_UTF7)
7059 return "CP_UTF7";
7060 if (code_page == CP_UTF8)
7061 return "CP_UTF8";
7062
7063 *obj = PyBytes_FromFormat("cp%u", code_page);
7064 if (*obj == NULL)
7065 return NULL;
7066 return PyBytes_AS_STRING(*obj);
7067}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007068
Victor Stinner3a50e702011-10-18 21:21:00 +02007069static DWORD
7070decode_code_page_flags(UINT code_page)
7071{
7072 if (code_page == CP_UTF7) {
7073 /* The CP_UTF7 decoder only supports flags=0 */
7074 return 0;
7075 }
7076 else
7077 return MB_ERR_INVALID_CHARS;
7078}
7079
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007081 * Decode a byte string from a Windows code page into unicode object in strict
7082 * mode.
7083 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007084 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7085 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007087static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007088decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007089 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 const char *in,
7091 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092{
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007094 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007096
7097 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007098 assert(insize > 0);
7099 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7100 if (outsize <= 0)
7101 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102
7103 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007104 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007105 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007106 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007107 if (*v == NULL)
7108 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007109 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110 }
7111 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007112 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007114 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007115 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007116 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007117 }
7118
7119 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007120 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7121 if (outsize <= 0)
7122 goto error;
7123 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007124
Victor Stinner3a50e702011-10-18 21:21:00 +02007125error:
7126 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7127 return -2;
7128 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007129 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007130}
7131
Victor Stinner3a50e702011-10-18 21:21:00 +02007132/*
7133 * Decode a byte string from a code page into unicode object with an error
7134 * handler.
7135 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007136 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007137 * UnicodeDecodeError exception and returns -1 on error.
7138 */
7139static int
7140decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007141 PyObject **v,
7142 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007143 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007144{
7145 const char *startin = in;
7146 const char *endin = in + size;
7147 const DWORD flags = decode_code_page_flags(code_page);
7148 /* Ideally, we should get reason from FormatMessage. This is the Windows
7149 2000 English version of the message. */
7150 const char *reason = "No mapping for the Unicode character exists "
7151 "in the target code page.";
7152 /* each step cannot decode more than 1 character, but a character can be
7153 represented as a surrogate pair */
7154 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007155 int insize;
7156 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007157 PyObject *errorHandler = NULL;
7158 PyObject *exc = NULL;
7159 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007160 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007161 DWORD err;
7162 int ret = -1;
7163
7164 assert(size > 0);
7165
7166 encoding = code_page_name(code_page, &encoding_obj);
7167 if (encoding == NULL)
7168 return -1;
7169
Victor Stinner7d00cc12014-03-17 23:08:06 +01007170 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007171 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7172 UnicodeDecodeError. */
7173 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7174 if (exc != NULL) {
7175 PyCodec_StrictErrors(exc);
7176 Py_CLEAR(exc);
7177 }
7178 goto error;
7179 }
7180
7181 if (*v == NULL) {
7182 /* Create unicode object */
7183 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7184 PyErr_NoMemory();
7185 goto error;
7186 }
Victor Stinnerab595942011-12-17 04:59:06 +01007187 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007188 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007189 if (*v == NULL)
7190 goto error;
7191 startout = PyUnicode_AS_UNICODE(*v);
7192 }
7193 else {
7194 /* Extend unicode object */
7195 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7196 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7197 PyErr_NoMemory();
7198 goto error;
7199 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007200 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 goto error;
7202 startout = PyUnicode_AS_UNICODE(*v) + n;
7203 }
7204
7205 /* Decode the byte string character per character */
7206 out = startout;
7207 while (in < endin)
7208 {
7209 /* Decode a character */
7210 insize = 1;
7211 do
7212 {
7213 outsize = MultiByteToWideChar(code_page, flags,
7214 in, insize,
7215 buffer, Py_ARRAY_LENGTH(buffer));
7216 if (outsize > 0)
7217 break;
7218 err = GetLastError();
7219 if (err != ERROR_NO_UNICODE_TRANSLATION
7220 && err != ERROR_INSUFFICIENT_BUFFER)
7221 {
7222 PyErr_SetFromWindowsErr(0);
7223 goto error;
7224 }
7225 insize++;
7226 }
7227 /* 4=maximum length of a UTF-8 sequence */
7228 while (insize <= 4 && (in + insize) <= endin);
7229
7230 if (outsize <= 0) {
7231 Py_ssize_t startinpos, endinpos, outpos;
7232
Victor Stinner7d00cc12014-03-17 23:08:06 +01007233 /* last character in partial decode? */
7234 if (in + insize >= endin && !final)
7235 break;
7236
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 startinpos = in - startin;
7238 endinpos = startinpos + 1;
7239 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007240 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 errors, &errorHandler,
7242 encoding, reason,
7243 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007244 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 {
7246 goto error;
7247 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007248 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 }
7250 else {
7251 in += insize;
7252 memcpy(out, buffer, outsize * sizeof(wchar_t));
7253 out += outsize;
7254 }
7255 }
7256
7257 /* write a NUL character at the end */
7258 *out = 0;
7259
7260 /* Extend unicode object */
7261 outsize = out - startout;
7262 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007263 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007265 /* (in - startin) <= size and size is an int */
7266 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007267
7268error:
7269 Py_XDECREF(encoding_obj);
7270 Py_XDECREF(errorHandler);
7271 Py_XDECREF(exc);
7272 return ret;
7273}
7274
Victor Stinner3a50e702011-10-18 21:21:00 +02007275static PyObject *
7276decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007277 const char *s, Py_ssize_t size,
7278 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007279{
Victor Stinner76a31a62011-11-04 00:05:13 +01007280 PyObject *v = NULL;
7281 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 if (code_page < 0) {
7284 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7285 return NULL;
7286 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007287 if (size < 0) {
7288 PyErr_BadInternalCall();
7289 return NULL;
7290 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007291
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007292 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007293 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007294
Victor Stinner76a31a62011-11-04 00:05:13 +01007295 do
7296 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007297#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007298 if (size > INT_MAX) {
7299 chunk_size = INT_MAX;
7300 final = 0;
7301 done = 0;
7302 }
7303 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007304#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007305 {
7306 chunk_size = (int)size;
7307 final = (consumed == NULL);
7308 done = 1;
7309 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007310
Victor Stinner76a31a62011-11-04 00:05:13 +01007311 if (chunk_size == 0 && done) {
7312 if (v != NULL)
7313 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007314 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007315 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007316
Victor Stinner76a31a62011-11-04 00:05:13 +01007317 converted = decode_code_page_strict(code_page, &v,
7318 s, chunk_size);
7319 if (converted == -2)
7320 converted = decode_code_page_errors(code_page, &v,
7321 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007322 errors, final);
7323 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007324
7325 if (converted < 0) {
7326 Py_XDECREF(v);
7327 return NULL;
7328 }
7329
7330 if (consumed)
7331 *consumed += converted;
7332
7333 s += converted;
7334 size -= converted;
7335 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007336
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007337 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007338}
7339
Alexander Belopolsky40018472011-02-26 01:02:56 +00007340PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007341PyUnicode_DecodeCodePageStateful(int code_page,
7342 const char *s,
7343 Py_ssize_t size,
7344 const char *errors,
7345 Py_ssize_t *consumed)
7346{
7347 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7348}
7349
7350PyObject *
7351PyUnicode_DecodeMBCSStateful(const char *s,
7352 Py_ssize_t size,
7353 const char *errors,
7354 Py_ssize_t *consumed)
7355{
7356 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7357}
7358
7359PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007360PyUnicode_DecodeMBCS(const char *s,
7361 Py_ssize_t size,
7362 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007363{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007364 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7365}
7366
Victor Stinner3a50e702011-10-18 21:21:00 +02007367static DWORD
7368encode_code_page_flags(UINT code_page, const char *errors)
7369{
7370 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007371 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007372 }
7373 else if (code_page == CP_UTF7) {
7374 /* CP_UTF7 only supports flags=0 */
7375 return 0;
7376 }
7377 else {
7378 if (errors != NULL && strcmp(errors, "replace") == 0)
7379 return 0;
7380 else
7381 return WC_NO_BEST_FIT_CHARS;
7382 }
7383}
7384
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007385/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007386 * Encode a Unicode string to a Windows code page into a byte string in strict
7387 * mode.
7388 *
7389 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007390 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007391 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007392static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007393encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007394 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007396{
Victor Stinner554f3f02010-06-16 23:33:54 +00007397 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 BOOL *pusedDefaultChar = &usedDefaultChar;
7399 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007400 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007401 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007402 const DWORD flags = encode_code_page_flags(code_page, NULL);
7403 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007404 /* Create a substring so that we can get the UTF-16 representation
7405 of just the slice under consideration. */
7406 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007407
Martin v. Löwis3d325192011-11-04 18:23:06 +01007408 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007409
Victor Stinner3a50e702011-10-18 21:21:00 +02007410 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007411 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007412 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007413 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007414
Victor Stinner2fc507f2011-11-04 20:06:39 +01007415 substring = PyUnicode_Substring(unicode, offset, offset+len);
7416 if (substring == NULL)
7417 return -1;
7418 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7419 if (p == NULL) {
7420 Py_DECREF(substring);
7421 return -1;
7422 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007423 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007424
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007425 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007427 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 NULL, 0,
7429 NULL, pusedDefaultChar);
7430 if (outsize <= 0)
7431 goto error;
7432 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007433 if (pusedDefaultChar && *pusedDefaultChar) {
7434 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007436 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007437
Victor Stinner3a50e702011-10-18 21:21:00 +02007438 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007439 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007441 if (*outbytes == NULL) {
7442 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007443 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007444 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007446 }
7447 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007448 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 const Py_ssize_t n = PyBytes_Size(*outbytes);
7450 if (outsize > PY_SSIZE_T_MAX - n) {
7451 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007452 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007453 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7456 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007460 }
7461
7462 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007464 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007465 out, outsize,
7466 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007467 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 if (outsize <= 0)
7469 goto error;
7470 if (pusedDefaultChar && *pusedDefaultChar)
7471 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007472 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007473
Victor Stinner3a50e702011-10-18 21:21:00 +02007474error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007475 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007476 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7477 return -2;
7478 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007479 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007480}
7481
Victor Stinner3a50e702011-10-18 21:21:00 +02007482/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007483 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007484 * error handler.
7485 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007486 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007487 * -1 on other error.
7488 */
7489static int
7490encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007491 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007492 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007493{
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007495 Py_ssize_t pos = unicode_offset;
7496 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007497 /* Ideally, we should get reason from FormatMessage. This is the Windows
7498 2000 English version of the message. */
7499 const char *reason = "invalid character";
7500 /* 4=maximum length of a UTF-8 sequence */
7501 char buffer[4];
7502 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7503 Py_ssize_t outsize;
7504 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 PyObject *errorHandler = NULL;
7506 PyObject *exc = NULL;
7507 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007508 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007509 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007510 PyObject *rep;
7511 int ret = -1;
7512
7513 assert(insize > 0);
7514
7515 encoding = code_page_name(code_page, &encoding_obj);
7516 if (encoding == NULL)
7517 return -1;
7518
7519 if (errors == NULL || strcmp(errors, "strict") == 0) {
7520 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7521 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007522 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007523 if (exc != NULL) {
7524 PyCodec_StrictErrors(exc);
7525 Py_DECREF(exc);
7526 }
7527 Py_XDECREF(encoding_obj);
7528 return -1;
7529 }
7530
7531 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7532 pusedDefaultChar = &usedDefaultChar;
7533 else
7534 pusedDefaultChar = NULL;
7535
7536 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7537 PyErr_NoMemory();
7538 goto error;
7539 }
7540 outsize = insize * Py_ARRAY_LENGTH(buffer);
7541
7542 if (*outbytes == NULL) {
7543 /* Create string object */
7544 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7545 if (*outbytes == NULL)
7546 goto error;
7547 out = PyBytes_AS_STRING(*outbytes);
7548 }
7549 else {
7550 /* Extend string object */
7551 Py_ssize_t n = PyBytes_Size(*outbytes);
7552 if (n > PY_SSIZE_T_MAX - outsize) {
7553 PyErr_NoMemory();
7554 goto error;
7555 }
7556 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7557 goto error;
7558 out = PyBytes_AS_STRING(*outbytes) + n;
7559 }
7560
7561 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007562 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007563 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007564 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7565 wchar_t chars[2];
7566 int charsize;
7567 if (ch < 0x10000) {
7568 chars[0] = (wchar_t)ch;
7569 charsize = 1;
7570 }
7571 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007572 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7573 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007574 charsize = 2;
7575 }
7576
Victor Stinner3a50e702011-10-18 21:21:00 +02007577 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007578 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007579 buffer, Py_ARRAY_LENGTH(buffer),
7580 NULL, pusedDefaultChar);
7581 if (outsize > 0) {
7582 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7583 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007584 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007585 memcpy(out, buffer, outsize);
7586 out += outsize;
7587 continue;
7588 }
7589 }
7590 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7591 PyErr_SetFromWindowsErr(0);
7592 goto error;
7593 }
7594
Victor Stinner3a50e702011-10-18 21:21:00 +02007595 rep = unicode_encode_call_errorhandler(
7596 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007597 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007598 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007599 if (rep == NULL)
7600 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007601 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007602
7603 if (PyBytes_Check(rep)) {
7604 outsize = PyBytes_GET_SIZE(rep);
7605 if (outsize != 1) {
7606 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7607 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7608 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7609 Py_DECREF(rep);
7610 goto error;
7611 }
7612 out = PyBytes_AS_STRING(*outbytes) + offset;
7613 }
7614 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7615 out += outsize;
7616 }
7617 else {
7618 Py_ssize_t i;
7619 enum PyUnicode_Kind kind;
7620 void *data;
7621
Benjamin Petersonbac79492012-01-14 13:34:47 -05007622 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007623 Py_DECREF(rep);
7624 goto error;
7625 }
7626
7627 outsize = PyUnicode_GET_LENGTH(rep);
7628 if (outsize != 1) {
7629 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7630 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7631 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7632 Py_DECREF(rep);
7633 goto error;
7634 }
7635 out = PyBytes_AS_STRING(*outbytes) + offset;
7636 }
7637 kind = PyUnicode_KIND(rep);
7638 data = PyUnicode_DATA(rep);
7639 for (i=0; i < outsize; i++) {
7640 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7641 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007642 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007643 encoding, unicode,
7644 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007645 "unable to encode error handler result to ASCII");
7646 Py_DECREF(rep);
7647 goto error;
7648 }
7649 *out = (unsigned char)ch;
7650 out++;
7651 }
7652 }
7653 Py_DECREF(rep);
7654 }
7655 /* write a NUL byte */
7656 *out = 0;
7657 outsize = out - PyBytes_AS_STRING(*outbytes);
7658 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7659 if (_PyBytes_Resize(outbytes, outsize) < 0)
7660 goto error;
7661 ret = 0;
7662
7663error:
7664 Py_XDECREF(encoding_obj);
7665 Py_XDECREF(errorHandler);
7666 Py_XDECREF(exc);
7667 return ret;
7668}
7669
Victor Stinner3a50e702011-10-18 21:21:00 +02007670static PyObject *
7671encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007672 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007673 const char *errors)
7674{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007675 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007676 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007677 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007678 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007679
Victor Stinner29dacf22015-01-26 16:41:32 +01007680 if (!PyUnicode_Check(unicode)) {
7681 PyErr_BadArgument();
7682 return NULL;
7683 }
7684
Benjamin Petersonbac79492012-01-14 13:34:47 -05007685 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007686 return NULL;
7687 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007688
Victor Stinner3a50e702011-10-18 21:21:00 +02007689 if (code_page < 0) {
7690 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7691 return NULL;
7692 }
7693
Martin v. Löwis3d325192011-11-04 18:23:06 +01007694 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007695 return PyBytes_FromStringAndSize(NULL, 0);
7696
Victor Stinner7581cef2011-11-03 22:32:33 +01007697 offset = 0;
7698 do
7699 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007700#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007701 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007702 chunks. */
7703 if (len > INT_MAX/2) {
7704 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007705 done = 0;
7706 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007707 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007708#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007709 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007710 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007711 done = 1;
7712 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007713
Victor Stinner76a31a62011-11-04 00:05:13 +01007714 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007715 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007716 errors);
7717 if (ret == -2)
7718 ret = encode_code_page_errors(code_page, &outbytes,
7719 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007720 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007721 if (ret < 0) {
7722 Py_XDECREF(outbytes);
7723 return NULL;
7724 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007725
Victor Stinner7581cef2011-11-03 22:32:33 +01007726 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007727 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007728 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007729
Victor Stinner3a50e702011-10-18 21:21:00 +02007730 return outbytes;
7731}
7732
7733PyObject *
7734PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7735 Py_ssize_t size,
7736 const char *errors)
7737{
Victor Stinner7581cef2011-11-03 22:32:33 +01007738 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007739 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007740 if (unicode == NULL)
7741 return NULL;
7742 res = encode_code_page(CP_ACP, unicode, errors);
7743 Py_DECREF(unicode);
7744 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007745}
7746
7747PyObject *
7748PyUnicode_EncodeCodePage(int code_page,
7749 PyObject *unicode,
7750 const char *errors)
7751{
Victor Stinner7581cef2011-11-03 22:32:33 +01007752 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007753}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007754
Alexander Belopolsky40018472011-02-26 01:02:56 +00007755PyObject *
7756PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007757{
Victor Stinner7581cef2011-11-03 22:32:33 +01007758 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007759}
7760
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007761#undef NEED_RETRY
7762
Steve Dowercc16be82016-09-08 10:35:16 -07007763#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007764
Guido van Rossumd57fd912000-03-10 22:53:23 +00007765/* --- Character Mapping Codec -------------------------------------------- */
7766
Victor Stinnerfb161b12013-04-18 01:44:27 +02007767static int
7768charmap_decode_string(const char *s,
7769 Py_ssize_t size,
7770 PyObject *mapping,
7771 const char *errors,
7772 _PyUnicodeWriter *writer)
7773{
7774 const char *starts = s;
7775 const char *e;
7776 Py_ssize_t startinpos, endinpos;
7777 PyObject *errorHandler = NULL, *exc = NULL;
7778 Py_ssize_t maplen;
7779 enum PyUnicode_Kind mapkind;
7780 void *mapdata;
7781 Py_UCS4 x;
7782 unsigned char ch;
7783
7784 if (PyUnicode_READY(mapping) == -1)
7785 return -1;
7786
7787 maplen = PyUnicode_GET_LENGTH(mapping);
7788 mapdata = PyUnicode_DATA(mapping);
7789 mapkind = PyUnicode_KIND(mapping);
7790
7791 e = s + size;
7792
7793 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7794 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7795 * is disabled in encoding aliases, latin1 is preferred because
7796 * its implementation is faster. */
7797 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7798 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7799 Py_UCS4 maxchar = writer->maxchar;
7800
7801 assert (writer->kind == PyUnicode_1BYTE_KIND);
7802 while (s < e) {
7803 ch = *s;
7804 x = mapdata_ucs1[ch];
7805 if (x > maxchar) {
7806 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7807 goto onError;
7808 maxchar = writer->maxchar;
7809 outdata = (Py_UCS1 *)writer->data;
7810 }
7811 outdata[writer->pos] = x;
7812 writer->pos++;
7813 ++s;
7814 }
7815 return 0;
7816 }
7817
7818 while (s < e) {
7819 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7820 enum PyUnicode_Kind outkind = writer->kind;
7821 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7822 if (outkind == PyUnicode_1BYTE_KIND) {
7823 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7824 Py_UCS4 maxchar = writer->maxchar;
7825 while (s < e) {
7826 ch = *s;
7827 x = mapdata_ucs2[ch];
7828 if (x > maxchar)
7829 goto Error;
7830 outdata[writer->pos] = x;
7831 writer->pos++;
7832 ++s;
7833 }
7834 break;
7835 }
7836 else if (outkind == PyUnicode_2BYTE_KIND) {
7837 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7838 while (s < e) {
7839 ch = *s;
7840 x = mapdata_ucs2[ch];
7841 if (x == 0xFFFE)
7842 goto Error;
7843 outdata[writer->pos] = x;
7844 writer->pos++;
7845 ++s;
7846 }
7847 break;
7848 }
7849 }
7850 ch = *s;
7851
7852 if (ch < maplen)
7853 x = PyUnicode_READ(mapkind, mapdata, ch);
7854 else
7855 x = 0xfffe; /* invalid value */
7856Error:
7857 if (x == 0xfffe)
7858 {
7859 /* undefined mapping */
7860 startinpos = s-starts;
7861 endinpos = startinpos+1;
7862 if (unicode_decode_call_errorhandler_writer(
7863 errors, &errorHandler,
7864 "charmap", "character maps to <undefined>",
7865 &starts, &e, &startinpos, &endinpos, &exc, &s,
7866 writer)) {
7867 goto onError;
7868 }
7869 continue;
7870 }
7871
7872 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7873 goto onError;
7874 ++s;
7875 }
7876 Py_XDECREF(errorHandler);
7877 Py_XDECREF(exc);
7878 return 0;
7879
7880onError:
7881 Py_XDECREF(errorHandler);
7882 Py_XDECREF(exc);
7883 return -1;
7884}
7885
7886static int
7887charmap_decode_mapping(const char *s,
7888 Py_ssize_t size,
7889 PyObject *mapping,
7890 const char *errors,
7891 _PyUnicodeWriter *writer)
7892{
7893 const char *starts = s;
7894 const char *e;
7895 Py_ssize_t startinpos, endinpos;
7896 PyObject *errorHandler = NULL, *exc = NULL;
7897 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007898 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007899
7900 e = s + size;
7901
7902 while (s < e) {
7903 ch = *s;
7904
7905 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7906 key = PyLong_FromLong((long)ch);
7907 if (key == NULL)
7908 goto onError;
7909
7910 item = PyObject_GetItem(mapping, key);
7911 Py_DECREF(key);
7912 if (item == NULL) {
7913 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7914 /* No mapping found means: mapping is undefined. */
7915 PyErr_Clear();
7916 goto Undefined;
7917 } else
7918 goto onError;
7919 }
7920
7921 /* Apply mapping */
7922 if (item == Py_None)
7923 goto Undefined;
7924 if (PyLong_Check(item)) {
7925 long value = PyLong_AS_LONG(item);
7926 if (value == 0xFFFE)
7927 goto Undefined;
7928 if (value < 0 || value > MAX_UNICODE) {
7929 PyErr_Format(PyExc_TypeError,
7930 "character mapping must be in range(0x%lx)",
7931 (unsigned long)MAX_UNICODE + 1);
7932 goto onError;
7933 }
7934
7935 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7936 goto onError;
7937 }
7938 else if (PyUnicode_Check(item)) {
7939 if (PyUnicode_READY(item) == -1)
7940 goto onError;
7941 if (PyUnicode_GET_LENGTH(item) == 1) {
7942 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7943 if (value == 0xFFFE)
7944 goto Undefined;
7945 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7946 goto onError;
7947 }
7948 else {
7949 writer->overallocate = 1;
7950 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7951 goto onError;
7952 }
7953 }
7954 else {
7955 /* wrong return value */
7956 PyErr_SetString(PyExc_TypeError,
7957 "character mapping must return integer, None or str");
7958 goto onError;
7959 }
7960 Py_CLEAR(item);
7961 ++s;
7962 continue;
7963
7964Undefined:
7965 /* undefined mapping */
7966 Py_CLEAR(item);
7967 startinpos = s-starts;
7968 endinpos = startinpos+1;
7969 if (unicode_decode_call_errorhandler_writer(
7970 errors, &errorHandler,
7971 "charmap", "character maps to <undefined>",
7972 &starts, &e, &startinpos, &endinpos, &exc, &s,
7973 writer)) {
7974 goto onError;
7975 }
7976 }
7977 Py_XDECREF(errorHandler);
7978 Py_XDECREF(exc);
7979 return 0;
7980
7981onError:
7982 Py_XDECREF(item);
7983 Py_XDECREF(errorHandler);
7984 Py_XDECREF(exc);
7985 return -1;
7986}
7987
Alexander Belopolsky40018472011-02-26 01:02:56 +00007988PyObject *
7989PyUnicode_DecodeCharmap(const char *s,
7990 Py_ssize_t size,
7991 PyObject *mapping,
7992 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007993{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007994 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007995
Guido van Rossumd57fd912000-03-10 22:53:23 +00007996 /* Default to Latin-1 */
7997 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999
Guido van Rossumd57fd912000-03-10 22:53:23 +00008000 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008001 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008002 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008003 writer.min_length = size;
8004 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008005 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008006
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008007 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008008 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8009 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008010 }
8011 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008012 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8013 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008014 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008015 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008016
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008018 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008019 return NULL;
8020}
8021
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008022/* Charmap encoding: the lookup table */
8023
Alexander Belopolsky40018472011-02-26 01:02:56 +00008024struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 PyObject_HEAD
8026 unsigned char level1[32];
8027 int count2, count3;
8028 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029};
8030
8031static PyObject*
8032encoding_map_size(PyObject *obj, PyObject* args)
8033{
8034 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008035 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008037}
8038
8039static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008040 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 PyDoc_STR("Return the size (in bytes) of this object") },
8042 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008043};
8044
8045static void
8046encoding_map_dealloc(PyObject* o)
8047{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008048 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008049}
8050
8051static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008052 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008053 "EncodingMap", /*tp_name*/
8054 sizeof(struct encoding_map), /*tp_basicsize*/
8055 0, /*tp_itemsize*/
8056 /* methods */
8057 encoding_map_dealloc, /*tp_dealloc*/
8058 0, /*tp_print*/
8059 0, /*tp_getattr*/
8060 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008061 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 0, /*tp_repr*/
8063 0, /*tp_as_number*/
8064 0, /*tp_as_sequence*/
8065 0, /*tp_as_mapping*/
8066 0, /*tp_hash*/
8067 0, /*tp_call*/
8068 0, /*tp_str*/
8069 0, /*tp_getattro*/
8070 0, /*tp_setattro*/
8071 0, /*tp_as_buffer*/
8072 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8073 0, /*tp_doc*/
8074 0, /*tp_traverse*/
8075 0, /*tp_clear*/
8076 0, /*tp_richcompare*/
8077 0, /*tp_weaklistoffset*/
8078 0, /*tp_iter*/
8079 0, /*tp_iternext*/
8080 encoding_map_methods, /*tp_methods*/
8081 0, /*tp_members*/
8082 0, /*tp_getset*/
8083 0, /*tp_base*/
8084 0, /*tp_dict*/
8085 0, /*tp_descr_get*/
8086 0, /*tp_descr_set*/
8087 0, /*tp_dictoffset*/
8088 0, /*tp_init*/
8089 0, /*tp_alloc*/
8090 0, /*tp_new*/
8091 0, /*tp_free*/
8092 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093};
8094
8095PyObject*
8096PyUnicode_BuildEncodingMap(PyObject* string)
8097{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098 PyObject *result;
8099 struct encoding_map *mresult;
8100 int i;
8101 int need_dict = 0;
8102 unsigned char level1[32];
8103 unsigned char level2[512];
8104 unsigned char *mlevel1, *mlevel2, *mlevel3;
8105 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008106 int kind;
8107 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008108 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008109 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008110
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008111 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008112 PyErr_BadArgument();
8113 return NULL;
8114 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008115 kind = PyUnicode_KIND(string);
8116 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008117 length = PyUnicode_GET_LENGTH(string);
8118 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119 memset(level1, 0xFF, sizeof level1);
8120 memset(level2, 0xFF, sizeof level2);
8121
8122 /* If there isn't a one-to-one mapping of NULL to \0,
8123 or if there are non-BMP characters, we need to use
8124 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008125 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008126 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008127 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008129 ch = PyUnicode_READ(kind, data, i);
8130 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008131 need_dict = 1;
8132 break;
8133 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008134 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008135 /* unmapped character */
8136 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008137 l1 = ch >> 11;
8138 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008139 if (level1[l1] == 0xFF)
8140 level1[l1] = count2++;
8141 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008142 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143 }
8144
8145 if (count2 >= 0xFF || count3 >= 0xFF)
8146 need_dict = 1;
8147
8148 if (need_dict) {
8149 PyObject *result = PyDict_New();
8150 PyObject *key, *value;
8151 if (!result)
8152 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008153 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008154 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008155 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008156 if (!key || !value)
8157 goto failed1;
8158 if (PyDict_SetItem(result, key, value) == -1)
8159 goto failed1;
8160 Py_DECREF(key);
8161 Py_DECREF(value);
8162 }
8163 return result;
8164 failed1:
8165 Py_XDECREF(key);
8166 Py_XDECREF(value);
8167 Py_DECREF(result);
8168 return NULL;
8169 }
8170
8171 /* Create a three-level trie */
8172 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8173 16*count2 + 128*count3 - 1);
8174 if (!result)
8175 return PyErr_NoMemory();
8176 PyObject_Init(result, &EncodingMapType);
8177 mresult = (struct encoding_map*)result;
8178 mresult->count2 = count2;
8179 mresult->count3 = count3;
8180 mlevel1 = mresult->level1;
8181 mlevel2 = mresult->level23;
8182 mlevel3 = mresult->level23 + 16*count2;
8183 memcpy(mlevel1, level1, 32);
8184 memset(mlevel2, 0xFF, 16*count2);
8185 memset(mlevel3, 0, 128*count3);
8186 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008187 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008188 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008189 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8190 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008191 /* unmapped character */
8192 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008193 o1 = ch>>11;
8194 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008195 i2 = 16*mlevel1[o1] + o2;
8196 if (mlevel2[i2] == 0xFF)
8197 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008198 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008199 i3 = 128*mlevel2[i2] + o3;
8200 mlevel3[i3] = i;
8201 }
8202 return result;
8203}
8204
8205static int
Victor Stinner22168992011-11-20 17:09:18 +01008206encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008207{
8208 struct encoding_map *map = (struct encoding_map*)mapping;
8209 int l1 = c>>11;
8210 int l2 = (c>>7) & 0xF;
8211 int l3 = c & 0x7F;
8212 int i;
8213
Victor Stinner22168992011-11-20 17:09:18 +01008214 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008216 if (c == 0)
8217 return 0;
8218 /* level 1*/
8219 i = map->level1[l1];
8220 if (i == 0xFF) {
8221 return -1;
8222 }
8223 /* level 2*/
8224 i = map->level23[16*i+l2];
8225 if (i == 0xFF) {
8226 return -1;
8227 }
8228 /* level 3 */
8229 i = map->level23[16*map->count2 + 128*i + l3];
8230 if (i == 0) {
8231 return -1;
8232 }
8233 return i;
8234}
8235
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236/* Lookup the character ch in the mapping. If the character
8237 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008238 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008239static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008240charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008241{
Christian Heimes217cfd12007-12-02 14:31:20 +00008242 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 PyObject *x;
8244
8245 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008246 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008247 x = PyObject_GetItem(mapping, w);
8248 Py_DECREF(w);
8249 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8251 /* No mapping found means: mapping is undefined. */
8252 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008253 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 } else
8255 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008256 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008257 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008259 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 long value = PyLong_AS_LONG(x);
8261 if (value < 0 || value > 255) {
8262 PyErr_SetString(PyExc_TypeError,
8263 "character mapping must be in range(256)");
8264 Py_DECREF(x);
8265 return NULL;
8266 }
8267 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008268 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008269 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008271 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 /* wrong return value */
8273 PyErr_Format(PyExc_TypeError,
8274 "character mapping must return integer, bytes or None, not %.400s",
8275 x->ob_type->tp_name);
8276 Py_DECREF(x);
8277 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278 }
8279}
8280
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008281static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008282charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008283{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008284 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8285 /* exponentially overallocate to minimize reallocations */
8286 if (requiredsize < 2*outsize)
8287 requiredsize = 2*outsize;
8288 if (_PyBytes_Resize(outobj, requiredsize))
8289 return -1;
8290 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008291}
8292
Benjamin Peterson14339b62009-01-31 16:36:08 +00008293typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008294 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008295} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008296/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008297 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008298 space is available. Return a new reference to the object that
8299 was put in the output buffer, or Py_None, if the mapping was undefined
8300 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008301 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008302static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008303charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008304 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008305{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008306 PyObject *rep;
8307 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008308 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008309
Christian Heimes90aa7642007-12-19 02:45:37 +00008310 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008311 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008313 if (res == -1)
8314 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 if (outsize<requiredsize)
8316 if (charmapencode_resize(outobj, outpos, requiredsize))
8317 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008318 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 outstart[(*outpos)++] = (char)res;
8320 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008321 }
8322
8323 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008326 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008327 Py_DECREF(rep);
8328 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008329 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 if (PyLong_Check(rep)) {
8331 Py_ssize_t requiredsize = *outpos+1;
8332 if (outsize<requiredsize)
8333 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8334 Py_DECREF(rep);
8335 return enc_EXCEPTION;
8336 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008337 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008338 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008339 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008340 else {
8341 const char *repchars = PyBytes_AS_STRING(rep);
8342 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8343 Py_ssize_t requiredsize = *outpos+repsize;
8344 if (outsize<requiredsize)
8345 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8346 Py_DECREF(rep);
8347 return enc_EXCEPTION;
8348 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008349 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008350 memcpy(outstart + *outpos, repchars, repsize);
8351 *outpos += repsize;
8352 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008354 Py_DECREF(rep);
8355 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356}
8357
8358/* handle an error in PyUnicode_EncodeCharmap
8359 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008360static int
8361charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008362 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008364 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008365 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366{
8367 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008368 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008369 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008370 enum PyUnicode_Kind kind;
8371 void *data;
8372 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008374 Py_ssize_t collstartpos = *inpos;
8375 Py_ssize_t collendpos = *inpos+1;
8376 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008377 const char *encoding = "charmap";
8378 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008379 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008380 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008381 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382
Benjamin Petersonbac79492012-01-14 13:34:47 -05008383 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008384 return -1;
8385 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 /* find all unencodable characters */
8387 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008388 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008389 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008390 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008391 val = encoding_map_lookup(ch, mapping);
8392 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 break;
8394 ++collendpos;
8395 continue;
8396 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008397
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008398 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8399 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 if (rep==NULL)
8401 return -1;
8402 else if (rep!=Py_None) {
8403 Py_DECREF(rep);
8404 break;
8405 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008406 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408 }
8409 /* cache callback name lookup
8410 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008411 if (*error_handler == _Py_ERROR_UNKNOWN)
8412 *error_handler = get_error_handler(errors);
8413
8414 switch (*error_handler) {
8415 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008416 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008417 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008418
8419 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008420 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 x = charmapencode_output('?', mapping, res, respos);
8422 if (x==enc_EXCEPTION) {
8423 return -1;
8424 }
8425 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008426 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 return -1;
8428 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008429 }
8430 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008431 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008432 *inpos = collendpos;
8433 break;
Victor Stinner50149202015-09-22 00:26:54 +02008434
8435 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008436 /* generate replacement (temporarily (mis)uses p) */
8437 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 char buffer[2+29+1+1];
8439 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008440 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 for (cp = buffer; *cp; ++cp) {
8442 x = charmapencode_output(*cp, mapping, res, respos);
8443 if (x==enc_EXCEPTION)
8444 return -1;
8445 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008446 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 return -1;
8448 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008449 }
8450 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008451 *inpos = collendpos;
8452 break;
Victor Stinner50149202015-09-22 00:26:54 +02008453
Benjamin Peterson14339b62009-01-31 16:36:08 +00008454 default:
Victor Stinner50149202015-09-22 00:26:54 +02008455 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008456 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008457 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008458 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008460 if (PyBytes_Check(repunicode)) {
8461 /* Directly copy bytes result to output. */
8462 Py_ssize_t outsize = PyBytes_Size(*res);
8463 Py_ssize_t requiredsize;
8464 repsize = PyBytes_Size(repunicode);
8465 requiredsize = *respos + repsize;
8466 if (requiredsize > outsize)
8467 /* Make room for all additional bytes. */
8468 if (charmapencode_resize(res, respos, requiredsize)) {
8469 Py_DECREF(repunicode);
8470 return -1;
8471 }
8472 memcpy(PyBytes_AsString(*res) + *respos,
8473 PyBytes_AsString(repunicode), repsize);
8474 *respos += repsize;
8475 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008476 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008477 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008478 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008479 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008480 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008481 Py_DECREF(repunicode);
8482 return -1;
8483 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008484 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008485 data = PyUnicode_DATA(repunicode);
8486 kind = PyUnicode_KIND(repunicode);
8487 for (index = 0; index < repsize; index++) {
8488 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8489 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008490 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008491 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 return -1;
8493 }
8494 else if (x==enc_FAILED) {
8495 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008496 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 return -1;
8498 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008499 }
8500 *inpos = newpos;
8501 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502 }
8503 return 0;
8504}
8505
Alexander Belopolsky40018472011-02-26 01:02:56 +00008506PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008507_PyUnicode_EncodeCharmap(PyObject *unicode,
8508 PyObject *mapping,
8509 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008510{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 /* output object */
8512 PyObject *res = NULL;
8513 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008514 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008515 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008517 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008518 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008519 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008520 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008521 void *data;
8522 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008523
Benjamin Petersonbac79492012-01-14 13:34:47 -05008524 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008525 return NULL;
8526 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008527 data = PyUnicode_DATA(unicode);
8528 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008529
Guido van Rossumd57fd912000-03-10 22:53:23 +00008530 /* Default to Latin-1 */
8531 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008532 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008533
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008534 /* allocate enough for a simple encoding without
8535 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008536 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 if (res == NULL)
8538 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008539 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008541
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008543 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008544 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008545 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 if (x==enc_EXCEPTION) /* error */
8547 goto onError;
8548 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008549 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008551 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 &res, &respos)) {
8553 goto onError;
8554 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008555 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 else
8557 /* done with this character => adjust input position */
8558 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008560
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008562 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008563 if (_PyBytes_Resize(&res, respos) < 0)
8564 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008565
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008567 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 return res;
8569
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008571 Py_XDECREF(res);
8572 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008573 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008574 return NULL;
8575}
8576
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008577/* Deprecated */
8578PyObject *
8579PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8580 Py_ssize_t size,
8581 PyObject *mapping,
8582 const char *errors)
8583{
8584 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008585 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008586 if (unicode == NULL)
8587 return NULL;
8588 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8589 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008590 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008591}
8592
Alexander Belopolsky40018472011-02-26 01:02:56 +00008593PyObject *
8594PyUnicode_AsCharmapString(PyObject *unicode,
8595 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596{
8597 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 PyErr_BadArgument();
8599 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008601 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008602}
8603
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008604/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008605static void
8606make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008608 Py_ssize_t startpos, Py_ssize_t endpos,
8609 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008610{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008611 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 *exceptionObject = _PyUnicodeTranslateError_Create(
8613 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008614 }
8615 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8617 goto onError;
8618 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8619 goto onError;
8620 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8621 goto onError;
8622 return;
8623 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008624 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625 }
8626}
8627
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628/* error handling callback helper:
8629 build arguments, call the callback and check the arguments,
8630 put the result into newpos and return the replacement string, which
8631 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008632static PyObject *
8633unicode_translate_call_errorhandler(const char *errors,
8634 PyObject **errorHandler,
8635 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008637 Py_ssize_t startpos, Py_ssize_t endpos,
8638 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008640 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008642 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 PyObject *restuple;
8644 PyObject *resunicode;
8645
8646 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008648 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650 }
8651
8652 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008653 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008656
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008657 restuple = PyObject_CallFunctionObjArgs(
8658 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008660 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008662 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 Py_DECREF(restuple);
8664 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008666 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 &resunicode, &i_newpos)) {
8668 Py_DECREF(restuple);
8669 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008670 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008671 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008673 else
8674 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008676 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 Py_DECREF(restuple);
8678 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008679 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008680 Py_INCREF(resunicode);
8681 Py_DECREF(restuple);
8682 return resunicode;
8683}
8684
8685/* Lookup the character ch in the mapping and put the result in result,
8686 which must be decrefed by the caller.
8687 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008688static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008690{
Christian Heimes217cfd12007-12-02 14:31:20 +00008691 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008692 PyObject *x;
8693
8694 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 x = PyObject_GetItem(mapping, w);
8697 Py_DECREF(w);
8698 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008699 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8700 /* No mapping found means: use 1:1 mapping. */
8701 PyErr_Clear();
8702 *result = NULL;
8703 return 0;
8704 } else
8705 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008706 }
8707 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008708 *result = x;
8709 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008710 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008711 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008713 if (value < 0 || value > MAX_UNICODE) {
8714 PyErr_Format(PyExc_ValueError,
8715 "character mapping must be in range(0x%x)",
8716 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 Py_DECREF(x);
8718 return -1;
8719 }
8720 *result = x;
8721 return 0;
8722 }
8723 else if (PyUnicode_Check(x)) {
8724 *result = x;
8725 return 0;
8726 }
8727 else {
8728 /* wrong return value */
8729 PyErr_SetString(PyExc_TypeError,
8730 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008731 Py_DECREF(x);
8732 return -1;
8733 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008734}
Victor Stinner1194ea02014-04-04 19:37:40 +02008735
8736/* lookup the character, write the result into the writer.
8737 Return 1 if the result was written into the writer, return 0 if the mapping
8738 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008739static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008740charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8741 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008742{
Victor Stinner1194ea02014-04-04 19:37:40 +02008743 PyObject *item;
8744
8745 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008746 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008747
8748 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008750 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008752 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008753 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008754 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008755
8756 if (item == Py_None) {
8757 Py_DECREF(item);
8758 return 0;
8759 }
8760
8761 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008762 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8763 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8764 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008765 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8766 Py_DECREF(item);
8767 return -1;
8768 }
8769 Py_DECREF(item);
8770 return 1;
8771 }
8772
8773 if (!PyUnicode_Check(item)) {
8774 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008775 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008776 }
8777
8778 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8779 Py_DECREF(item);
8780 return -1;
8781 }
8782
8783 Py_DECREF(item);
8784 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008785}
8786
Victor Stinner89a76ab2014-04-05 11:44:04 +02008787static int
8788unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8789 Py_UCS1 *translate)
8790{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008791 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008792 int ret = 0;
8793
Victor Stinner89a76ab2014-04-05 11:44:04 +02008794 if (charmaptranslate_lookup(ch, mapping, &item)) {
8795 return -1;
8796 }
8797
8798 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008799 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008800 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008801 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008802 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008803 /* not found => default to 1:1 mapping */
8804 translate[ch] = ch;
8805 return 1;
8806 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008807 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008808 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008809 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8810 used it */
8811 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008812 /* invalid character or character outside ASCII:
8813 skip the fast translate */
8814 goto exit;
8815 }
8816 translate[ch] = (Py_UCS1)replace;
8817 }
8818 else if (PyUnicode_Check(item)) {
8819 Py_UCS4 replace;
8820
8821 if (PyUnicode_READY(item) == -1) {
8822 Py_DECREF(item);
8823 return -1;
8824 }
8825 if (PyUnicode_GET_LENGTH(item) != 1)
8826 goto exit;
8827
8828 replace = PyUnicode_READ_CHAR(item, 0);
8829 if (replace > 127)
8830 goto exit;
8831 translate[ch] = (Py_UCS1)replace;
8832 }
8833 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008834 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008835 goto exit;
8836 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008837 ret = 1;
8838
Benjamin Peterson1365de72014-04-07 20:15:41 -04008839 exit:
8840 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008841 return ret;
8842}
8843
8844/* Fast path for ascii => ascii translation. Return 1 if the whole string
8845 was translated into writer, return 0 if the input string was partially
8846 translated into writer, raise an exception and return -1 on error. */
8847static int
8848unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008849 _PyUnicodeWriter *writer, int ignore,
8850 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008851{
Victor Stinner872b2912014-04-05 14:27:07 +02008852 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008853 Py_ssize_t len;
8854 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008855 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008856
Victor Stinner89a76ab2014-04-05 11:44:04 +02008857 len = PyUnicode_GET_LENGTH(input);
8858
Victor Stinner872b2912014-04-05 14:27:07 +02008859 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008860
8861 in = PyUnicode_1BYTE_DATA(input);
8862 end = in + len;
8863
8864 assert(PyUnicode_IS_ASCII(writer->buffer));
8865 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8866 out = PyUnicode_1BYTE_DATA(writer->buffer);
8867
Victor Stinner872b2912014-04-05 14:27:07 +02008868 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008869 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008870 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008871 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008872 int translate = unicode_fast_translate_lookup(mapping, ch,
8873 ascii_table);
8874 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008875 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008876 if (translate == 0)
8877 goto exit;
8878 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008879 }
Victor Stinner872b2912014-04-05 14:27:07 +02008880 if (ch2 == 0xfe) {
8881 if (ignore)
8882 continue;
8883 goto exit;
8884 }
8885 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008886 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008887 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008888 }
Victor Stinner872b2912014-04-05 14:27:07 +02008889 res = 1;
8890
8891exit:
8892 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008893 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008894 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008895}
8896
Victor Stinner3222da22015-10-01 22:07:32 +02008897static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008898_PyUnicode_TranslateCharmap(PyObject *input,
8899 PyObject *mapping,
8900 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008901{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008902 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008903 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008904 Py_ssize_t size, i;
8905 int kind;
8906 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008907 _PyUnicodeWriter writer;
8908 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008909 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008910 PyObject *errorHandler = NULL;
8911 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008912 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008913 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008914
Guido van Rossumd57fd912000-03-10 22:53:23 +00008915 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008916 PyErr_BadArgument();
8917 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008918 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920 if (PyUnicode_READY(input) == -1)
8921 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008922 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008923 kind = PyUnicode_KIND(input);
8924 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008925
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008926 if (size == 0)
8927 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008928
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008929 /* allocate enough for a simple 1:1 translation without
8930 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008931 _PyUnicodeWriter_Init(&writer);
8932 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008933 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008934
Victor Stinner872b2912014-04-05 14:27:07 +02008935 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8936
Victor Stinner33798672016-03-01 21:59:58 +01008937 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008938 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008939 if (PyUnicode_IS_ASCII(input)) {
8940 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8941 if (res < 0) {
8942 _PyUnicodeWriter_Dealloc(&writer);
8943 return NULL;
8944 }
8945 if (res == 1)
8946 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008947 }
Victor Stinner33798672016-03-01 21:59:58 +01008948 else {
8949 i = 0;
8950 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008951
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008952 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008953 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008954 int translate;
8955 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8956 Py_ssize_t newpos;
8957 /* startpos for collecting untranslatable chars */
8958 Py_ssize_t collstart;
8959 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008960 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961
Victor Stinner1194ea02014-04-04 19:37:40 +02008962 ch = PyUnicode_READ(kind, data, i);
8963 translate = charmaptranslate_output(ch, mapping, &writer);
8964 if (translate < 0)
8965 goto onError;
8966
8967 if (translate != 0) {
8968 /* it worked => adjust input pointer */
8969 ++i;
8970 continue;
8971 }
8972
8973 /* untranslatable character */
8974 collstart = i;
8975 collend = i+1;
8976
8977 /* find all untranslatable characters */
8978 while (collend < size) {
8979 PyObject *x;
8980 ch = PyUnicode_READ(kind, data, collend);
8981 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008982 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008983 Py_XDECREF(x);
8984 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008985 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008986 ++collend;
8987 }
8988
8989 if (ignore) {
8990 i = collend;
8991 }
8992 else {
8993 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8994 reason, input, &exc,
8995 collstart, collend, &newpos);
8996 if (repunicode == NULL)
8997 goto onError;
8998 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008999 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009000 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009001 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009002 Py_DECREF(repunicode);
9003 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009004 }
9005 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009006 Py_XDECREF(exc);
9007 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009008 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009
Benjamin Peterson29060642009-01-31 22:14:21 +00009010 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009011 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009012 Py_XDECREF(exc);
9013 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009014 return NULL;
9015}
9016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009017/* Deprecated. Use PyUnicode_Translate instead. */
9018PyObject *
9019PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9020 Py_ssize_t size,
9021 PyObject *mapping,
9022 const char *errors)
9023{
Christian Heimes5f520f42012-09-11 14:03:25 +02009024 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009025 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009026 if (!unicode)
9027 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009028 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9029 Py_DECREF(unicode);
9030 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031}
9032
Alexander Belopolsky40018472011-02-26 01:02:56 +00009033PyObject *
9034PyUnicode_Translate(PyObject *str,
9035 PyObject *mapping,
9036 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009037{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009038 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009039 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009040 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009041}
Tim Petersced69f82003-09-16 20:30:58 +00009042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043PyObject *
9044_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9045{
9046 if (!PyUnicode_Check(unicode)) {
9047 PyErr_BadInternalCall();
9048 return NULL;
9049 }
9050 if (PyUnicode_READY(unicode) == -1)
9051 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009052 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 /* If the string is already ASCII, just return the same string */
9054 Py_INCREF(unicode);
9055 return unicode;
9056 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009057
9058 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9059 PyObject *result = PyUnicode_New(len, 127);
9060 if (result == NULL) {
9061 return NULL;
9062 }
9063
9064 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9065 int kind = PyUnicode_KIND(unicode);
9066 const void *data = PyUnicode_DATA(unicode);
9067 Py_ssize_t i;
9068 for (i = 0; i < len; ++i) {
9069 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9070 if (ch < 127) {
9071 out[i] = ch;
9072 }
9073 else if (Py_UNICODE_ISSPACE(ch)) {
9074 out[i] = ' ';
9075 }
9076 else {
9077 int decimal = Py_UNICODE_TODECIMAL(ch);
9078 if (decimal < 0) {
9079 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009080 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009081 _PyUnicode_LENGTH(result) = i + 1;
9082 break;
9083 }
9084 out[i] = '0' + decimal;
9085 }
9086 }
9087
INADA Naoki16dfca42018-07-14 12:06:43 +09009088 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009089 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009090}
9091
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009092PyObject *
9093PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9094 Py_ssize_t length)
9095{
Victor Stinnerf0124502011-11-21 23:12:56 +01009096 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009097 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009098 Py_UCS4 maxchar;
9099 enum PyUnicode_Kind kind;
9100 void *data;
9101
Victor Stinner99d7ad02012-02-22 13:37:39 +01009102 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009103 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009104 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009105 if (ch > 127) {
9106 int decimal = Py_UNICODE_TODECIMAL(ch);
9107 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009108 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009109 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009110 }
9111 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009112
9113 /* Copy to a new string */
9114 decimal = PyUnicode_New(length, maxchar);
9115 if (decimal == NULL)
9116 return decimal;
9117 kind = PyUnicode_KIND(decimal);
9118 data = PyUnicode_DATA(decimal);
9119 /* Iterate over code points */
9120 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009121 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009122 if (ch > 127) {
9123 int decimal = Py_UNICODE_TODECIMAL(ch);
9124 if (decimal >= 0)
9125 ch = '0' + decimal;
9126 }
9127 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009128 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009129 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009130}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009131/* --- Decimal Encoder ---------------------------------------------------- */
9132
Alexander Belopolsky40018472011-02-26 01:02:56 +00009133int
9134PyUnicode_EncodeDecimal(Py_UNICODE *s,
9135 Py_ssize_t length,
9136 char *output,
9137 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009138{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009139 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009140 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009141 enum PyUnicode_Kind kind;
9142 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009143
9144 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009145 PyErr_BadArgument();
9146 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009147 }
9148
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009149 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009150 if (unicode == NULL)
9151 return -1;
9152
Victor Stinner42bf7752011-11-21 22:52:58 +01009153 kind = PyUnicode_KIND(unicode);
9154 data = PyUnicode_DATA(unicode);
9155
Victor Stinnerb84d7232011-11-22 01:50:07 +01009156 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009157 PyObject *exc;
9158 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009159 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009160 Py_ssize_t startpos;
9161
9162 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009163
Benjamin Peterson29060642009-01-31 22:14:21 +00009164 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009165 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009166 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009167 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009168 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009169 decimal = Py_UNICODE_TODECIMAL(ch);
9170 if (decimal >= 0) {
9171 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009172 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009173 continue;
9174 }
9175 if (0 < ch && ch < 256) {
9176 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009177 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009178 continue;
9179 }
Victor Stinner6345be92011-11-25 20:09:01 +01009180
Victor Stinner42bf7752011-11-21 22:52:58 +01009181 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009182 exc = NULL;
9183 raise_encode_exception(&exc, "decimal", unicode,
9184 startpos, startpos+1,
9185 "invalid decimal Unicode string");
9186 Py_XDECREF(exc);
9187 Py_DECREF(unicode);
9188 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009189 }
9190 /* 0-terminate the output string */
9191 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009192 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009193 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009194}
9195
Guido van Rossumd57fd912000-03-10 22:53:23 +00009196/* --- Helpers ------------------------------------------------------------ */
9197
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009198/* helper macro to fixup start/end slice values */
9199#define ADJUST_INDICES(start, end, len) \
9200 if (end > len) \
9201 end = len; \
9202 else if (end < 0) { \
9203 end += len; \
9204 if (end < 0) \
9205 end = 0; \
9206 } \
9207 if (start < 0) { \
9208 start += len; \
9209 if (start < 0) \
9210 start = 0; \
9211 }
9212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009214any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009216 Py_ssize_t end,
9217 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009219 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220 void *buf1, *buf2;
9221 Py_ssize_t len1, len2, result;
9222
9223 kind1 = PyUnicode_KIND(s1);
9224 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009225 if (kind1 < kind2)
9226 return -1;
9227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228 len1 = PyUnicode_GET_LENGTH(s1);
9229 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009230 ADJUST_INDICES(start, end, len1);
9231 if (end - start < len2)
9232 return -1;
9233
9234 buf1 = PyUnicode_DATA(s1);
9235 buf2 = PyUnicode_DATA(s2);
9236 if (len2 == 1) {
9237 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9238 result = findchar((const char *)buf1 + kind1*start,
9239 kind1, end - start, ch, direction);
9240 if (result == -1)
9241 return -1;
9242 else
9243 return start + result;
9244 }
9245
9246 if (kind2 != kind1) {
9247 buf2 = _PyUnicode_AsKind(s2, kind1);
9248 if (!buf2)
9249 return -2;
9250 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009251
Victor Stinner794d5672011-10-10 03:21:36 +02009252 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009253 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009254 case PyUnicode_1BYTE_KIND:
9255 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9256 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9257 else
9258 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9259 break;
9260 case PyUnicode_2BYTE_KIND:
9261 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9262 break;
9263 case PyUnicode_4BYTE_KIND:
9264 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9265 break;
9266 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009267 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009268 }
9269 }
9270 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009271 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009272 case PyUnicode_1BYTE_KIND:
9273 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9274 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9275 else
9276 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9277 break;
9278 case PyUnicode_2BYTE_KIND:
9279 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9280 break;
9281 case PyUnicode_4BYTE_KIND:
9282 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9283 break;
9284 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009285 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 }
9288
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009289 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009290 PyMem_Free(buf2);
9291
9292 return result;
9293}
9294
9295Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009296_PyUnicode_InsertThousandsGrouping(
9297 PyObject *unicode, Py_ssize_t index,
9298 Py_ssize_t n_buffer,
9299 void *digits, Py_ssize_t n_digits,
9300 Py_ssize_t min_width,
9301 const char *grouping, PyObject *thousands_sep,
9302 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303{
Victor Stinner41a863c2012-02-24 00:37:51 +01009304 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009305 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009306 Py_ssize_t thousands_sep_len;
9307 Py_ssize_t len;
9308
9309 if (unicode != NULL) {
9310 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009311 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009312 }
9313 else {
9314 kind = PyUnicode_1BYTE_KIND;
9315 data = NULL;
9316 }
9317 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9318 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9319 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9320 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009321 if (thousands_sep_kind < kind) {
9322 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9323 if (!thousands_sep_data)
9324 return -1;
9325 }
9326 else {
9327 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9328 if (!data)
9329 return -1;
9330 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009331 }
9332
Benjamin Petersonead6b532011-12-20 17:23:42 -06009333 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009335 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009336 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009337 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009338 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009339 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009340 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009341 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009342 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009343 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009344 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009345 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009347 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009348 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009349 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009350 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009351 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009352 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009353 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009354 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009355 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009356 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009357 break;
9358 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009359 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009360 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009361 if (unicode != NULL && thousands_sep_kind != kind) {
9362 if (thousands_sep_kind < kind)
9363 PyMem_Free(thousands_sep_data);
9364 else
9365 PyMem_Free(data);
9366 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009367 if (unicode == NULL) {
9368 *maxchar = 127;
9369 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009370 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009371 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009372 }
9373 }
9374 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375}
9376
9377
Alexander Belopolsky40018472011-02-26 01:02:56 +00009378Py_ssize_t
9379PyUnicode_Count(PyObject *str,
9380 PyObject *substr,
9381 Py_ssize_t start,
9382 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009383{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009384 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009385 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 void *buf1 = NULL, *buf2 = NULL;
9387 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009388
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009389 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009390 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009391
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009392 kind1 = PyUnicode_KIND(str);
9393 kind2 = PyUnicode_KIND(substr);
9394 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009395 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009396
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009397 len1 = PyUnicode_GET_LENGTH(str);
9398 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009399 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009400 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009401 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009402
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009403 buf1 = PyUnicode_DATA(str);
9404 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009405 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009406 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009407 if (!buf2)
9408 goto onError;
9409 }
9410
9411 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009412 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009413 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009414 result = asciilib_count(
9415 ((Py_UCS1*)buf1) + start, end - start,
9416 buf2, len2, PY_SSIZE_T_MAX
9417 );
9418 else
9419 result = ucs1lib_count(
9420 ((Py_UCS1*)buf1) + start, end - start,
9421 buf2, len2, PY_SSIZE_T_MAX
9422 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 break;
9424 case PyUnicode_2BYTE_KIND:
9425 result = ucs2lib_count(
9426 ((Py_UCS2*)buf1) + start, end - start,
9427 buf2, len2, PY_SSIZE_T_MAX
9428 );
9429 break;
9430 case PyUnicode_4BYTE_KIND:
9431 result = ucs4lib_count(
9432 ((Py_UCS4*)buf1) + start, end - start,
9433 buf2, len2, PY_SSIZE_T_MAX
9434 );
9435 break;
9436 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009437 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009439
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009440 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441 PyMem_Free(buf2);
9442
Guido van Rossumd57fd912000-03-10 22:53:23 +00009443 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009445 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 PyMem_Free(buf2);
9447 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009448}
9449
Alexander Belopolsky40018472011-02-26 01:02:56 +00009450Py_ssize_t
9451PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009452 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009453 Py_ssize_t start,
9454 Py_ssize_t end,
9455 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009457 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009458 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009459
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009460 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461}
9462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463Py_ssize_t
9464PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9465 Py_ssize_t start, Py_ssize_t end,
9466 int direction)
9467{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009469 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 if (PyUnicode_READY(str) == -1)
9471 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009472 len = PyUnicode_GET_LENGTH(str);
9473 ADJUST_INDICES(start, end, len);
9474 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009475 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009477 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9478 kind, end-start, ch, direction);
9479 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009481 else
9482 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483}
9484
Alexander Belopolsky40018472011-02-26 01:02:56 +00009485static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009486tailmatch(PyObject *self,
9487 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009488 Py_ssize_t start,
9489 Py_ssize_t end,
9490 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 int kind_self;
9493 int kind_sub;
9494 void *data_self;
9495 void *data_sub;
9496 Py_ssize_t offset;
9497 Py_ssize_t i;
9498 Py_ssize_t end_sub;
9499
9500 if (PyUnicode_READY(self) == -1 ||
9501 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009502 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9505 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009507 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009509 if (PyUnicode_GET_LENGTH(substring) == 0)
9510 return 1;
9511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 kind_self = PyUnicode_KIND(self);
9513 data_self = PyUnicode_DATA(self);
9514 kind_sub = PyUnicode_KIND(substring);
9515 data_sub = PyUnicode_DATA(substring);
9516 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9517
9518 if (direction > 0)
9519 offset = end;
9520 else
9521 offset = start;
9522
9523 if (PyUnicode_READ(kind_self, data_self, offset) ==
9524 PyUnicode_READ(kind_sub, data_sub, 0) &&
9525 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9526 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9527 /* If both are of the same kind, memcmp is sufficient */
9528 if (kind_self == kind_sub) {
9529 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009530 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 data_sub,
9532 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009533 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009534 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009535 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009536 else {
9537 /* We do not need to compare 0 and len(substring)-1 because
9538 the if statement above ensured already that they are equal
9539 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009540 for (i = 1; i < end_sub; ++i) {
9541 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9542 PyUnicode_READ(kind_sub, data_sub, i))
9543 return 0;
9544 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009545 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547 }
9548
9549 return 0;
9550}
9551
Alexander Belopolsky40018472011-02-26 01:02:56 +00009552Py_ssize_t
9553PyUnicode_Tailmatch(PyObject *str,
9554 PyObject *substr,
9555 Py_ssize_t start,
9556 Py_ssize_t end,
9557 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009559 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009560 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009561
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009562 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563}
9564
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009565static PyObject *
9566ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009568 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9569 char *resdata, *data = PyUnicode_DATA(self);
9570 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009571
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009572 res = PyUnicode_New(len, 127);
9573 if (res == NULL)
9574 return NULL;
9575 resdata = PyUnicode_DATA(res);
9576 if (lower)
9577 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009578 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009579 _Py_bytes_upper(resdata, data, len);
9580 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009581}
9582
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009583static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009584handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009585{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009586 Py_ssize_t j;
9587 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009588 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009589 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009590
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009591 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9592
9593 where ! is a negation and \p{xxx} is a character with property xxx.
9594 */
9595 for (j = i - 1; j >= 0; j--) {
9596 c = PyUnicode_READ(kind, data, j);
9597 if (!_PyUnicode_IsCaseIgnorable(c))
9598 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009599 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009600 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9601 if (final_sigma) {
9602 for (j = i + 1; j < length; j++) {
9603 c = PyUnicode_READ(kind, data, j);
9604 if (!_PyUnicode_IsCaseIgnorable(c))
9605 break;
9606 }
9607 final_sigma = j == length || !_PyUnicode_IsCased(c);
9608 }
9609 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009610}
9611
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009612static int
9613lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9614 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009615{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009616 /* Obscure special case. */
9617 if (c == 0x3A3) {
9618 mapped[0] = handle_capital_sigma(kind, data, length, i);
9619 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009620 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009621 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009622}
9623
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009624static Py_ssize_t
9625do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009627 Py_ssize_t i, k = 0;
9628 int n_res, j;
9629 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009630
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009631 c = PyUnicode_READ(kind, data, 0);
9632 n_res = _PyUnicode_ToUpperFull(c, mapped);
9633 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009634 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009636 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637 for (i = 1; i < length; i++) {
9638 c = PyUnicode_READ(kind, data, i);
9639 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9640 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009641 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009642 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009643 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009644 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009645 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009646}
9647
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009648static Py_ssize_t
9649do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9650 Py_ssize_t i, k = 0;
9651
9652 for (i = 0; i < length; i++) {
9653 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9654 int n_res, j;
9655 if (Py_UNICODE_ISUPPER(c)) {
9656 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9657 }
9658 else if (Py_UNICODE_ISLOWER(c)) {
9659 n_res = _PyUnicode_ToUpperFull(c, mapped);
9660 }
9661 else {
9662 n_res = 1;
9663 mapped[0] = c;
9664 }
9665 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009666 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009667 res[k++] = mapped[j];
9668 }
9669 }
9670 return k;
9671}
9672
9673static Py_ssize_t
9674do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9675 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009676{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009677 Py_ssize_t i, k = 0;
9678
9679 for (i = 0; i < length; i++) {
9680 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9681 int n_res, j;
9682 if (lower)
9683 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9684 else
9685 n_res = _PyUnicode_ToUpperFull(c, mapped);
9686 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009687 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009688 res[k++] = mapped[j];
9689 }
9690 }
9691 return k;
9692}
9693
9694static Py_ssize_t
9695do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9696{
9697 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9698}
9699
9700static Py_ssize_t
9701do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9702{
9703 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9704}
9705
Benjamin Petersone51757f2012-01-12 21:10:29 -05009706static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009707do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9708{
9709 Py_ssize_t i, k = 0;
9710
9711 for (i = 0; i < length; i++) {
9712 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9713 Py_UCS4 mapped[3];
9714 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9715 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009716 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009717 res[k++] = mapped[j];
9718 }
9719 }
9720 return k;
9721}
9722
9723static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009724do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9725{
9726 Py_ssize_t i, k = 0;
9727 int previous_is_cased;
9728
9729 previous_is_cased = 0;
9730 for (i = 0; i < length; i++) {
9731 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9732 Py_UCS4 mapped[3];
9733 int n_res, j;
9734
9735 if (previous_is_cased)
9736 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9737 else
9738 n_res = _PyUnicode_ToTitleFull(c, mapped);
9739
9740 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009741 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009742 res[k++] = mapped[j];
9743 }
9744
9745 previous_is_cased = _PyUnicode_IsCased(c);
9746 }
9747 return k;
9748}
9749
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009750static PyObject *
9751case_operation(PyObject *self,
9752 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9753{
9754 PyObject *res = NULL;
9755 Py_ssize_t length, newlength = 0;
9756 int kind, outkind;
9757 void *data, *outdata;
9758 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9759
Benjamin Petersoneea48462012-01-16 14:28:50 -05009760 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009761
9762 kind = PyUnicode_KIND(self);
9763 data = PyUnicode_DATA(self);
9764 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009765 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009766 PyErr_SetString(PyExc_OverflowError, "string is too long");
9767 return NULL;
9768 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009769 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009770 if (tmp == NULL)
9771 return PyErr_NoMemory();
9772 newlength = perform(kind, data, length, tmp, &maxchar);
9773 res = PyUnicode_New(newlength, maxchar);
9774 if (res == NULL)
9775 goto leave;
9776 tmpend = tmp + newlength;
9777 outdata = PyUnicode_DATA(res);
9778 outkind = PyUnicode_KIND(res);
9779 switch (outkind) {
9780 case PyUnicode_1BYTE_KIND:
9781 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9782 break;
9783 case PyUnicode_2BYTE_KIND:
9784 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9785 break;
9786 case PyUnicode_4BYTE_KIND:
9787 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9788 break;
9789 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009790 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009791 }
9792 leave:
9793 PyMem_FREE(tmp);
9794 return res;
9795}
9796
Tim Peters8ce9f162004-08-27 01:49:32 +00009797PyObject *
9798PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009799{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009800 PyObject *res;
9801 PyObject *fseq;
9802 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009803 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009804
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009805 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009806 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009807 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009808 }
9809
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009810 /* NOTE: the following code can't call back into Python code,
9811 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009812 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009813
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009814 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009815 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009816 res = _PyUnicode_JoinArray(separator, items, seqlen);
9817 Py_DECREF(fseq);
9818 return res;
9819}
9820
9821PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009822_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009823{
9824 PyObject *res = NULL; /* the result */
9825 PyObject *sep = NULL;
9826 Py_ssize_t seplen;
9827 PyObject *item;
9828 Py_ssize_t sz, i, res_offset;
9829 Py_UCS4 maxchar;
9830 Py_UCS4 item_maxchar;
9831 int use_memcpy;
9832 unsigned char *res_data = NULL, *sep_data = NULL;
9833 PyObject *last_obj;
9834 unsigned int kind = 0;
9835
Tim Peters05eba1f2004-08-27 21:32:02 +00009836 /* If empty sequence, return u"". */
9837 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009838 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009839 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009840
Tim Peters05eba1f2004-08-27 21:32:02 +00009841 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009842 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009843 if (seqlen == 1) {
9844 if (PyUnicode_CheckExact(items[0])) {
9845 res = items[0];
9846 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009847 return res;
9848 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009849 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009850 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009851 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009852 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009853 /* Set up sep and seplen */
9854 if (separator == NULL) {
9855 /* fall back to a blank space separator */
9856 sep = PyUnicode_FromOrdinal(' ');
9857 if (!sep)
9858 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009859 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009860 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009861 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009862 else {
9863 if (!PyUnicode_Check(separator)) {
9864 PyErr_Format(PyExc_TypeError,
9865 "separator: expected str instance,"
9866 " %.80s found",
9867 Py_TYPE(separator)->tp_name);
9868 goto onError;
9869 }
9870 if (PyUnicode_READY(separator))
9871 goto onError;
9872 sep = separator;
9873 seplen = PyUnicode_GET_LENGTH(separator);
9874 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9875 /* inc refcount to keep this code path symmetric with the
9876 above case of a blank separator */
9877 Py_INCREF(sep);
9878 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009879 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009880 }
9881
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009882 /* There are at least two things to join, or else we have a subclass
9883 * of str in the sequence.
9884 * Do a pre-pass to figure out the total amount of space we'll
9885 * need (sz), and see whether all argument are strings.
9886 */
9887 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009888#ifdef Py_DEBUG
9889 use_memcpy = 0;
9890#else
9891 use_memcpy = 1;
9892#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009893 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009894 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009895 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009896 if (!PyUnicode_Check(item)) {
9897 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009898 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009899 " %.80s found",
9900 i, Py_TYPE(item)->tp_name);
9901 goto onError;
9902 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009903 if (PyUnicode_READY(item) == -1)
9904 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009905 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009906 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009907 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009908 if (i != 0) {
9909 add_sz += seplen;
9910 }
9911 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009912 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009913 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009914 goto onError;
9915 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009916 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009917 if (use_memcpy && last_obj != NULL) {
9918 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9919 use_memcpy = 0;
9920 }
9921 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009922 }
Tim Petersced69f82003-09-16 20:30:58 +00009923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009924 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009925 if (res == NULL)
9926 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009927
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009928 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009929#ifdef Py_DEBUG
9930 use_memcpy = 0;
9931#else
9932 if (use_memcpy) {
9933 res_data = PyUnicode_1BYTE_DATA(res);
9934 kind = PyUnicode_KIND(res);
9935 if (seplen != 0)
9936 sep_data = PyUnicode_1BYTE_DATA(sep);
9937 }
9938#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009939 if (use_memcpy) {
9940 for (i = 0; i < seqlen; ++i) {
9941 Py_ssize_t itemlen;
9942 item = items[i];
9943
9944 /* Copy item, and maybe the separator. */
9945 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009946 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009947 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009948 kind * seplen);
9949 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009950 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009951
9952 itemlen = PyUnicode_GET_LENGTH(item);
9953 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009954 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009955 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009956 kind * itemlen);
9957 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009958 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009959 }
9960 assert(res_data == PyUnicode_1BYTE_DATA(res)
9961 + kind * PyUnicode_GET_LENGTH(res));
9962 }
9963 else {
9964 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9965 Py_ssize_t itemlen;
9966 item = items[i];
9967
9968 /* Copy item, and maybe the separator. */
9969 if (i && seplen != 0) {
9970 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9971 res_offset += seplen;
9972 }
9973
9974 itemlen = PyUnicode_GET_LENGTH(item);
9975 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009976 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009977 res_offset += itemlen;
9978 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009979 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009980 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009981 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009984 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009985 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009986
Benjamin Peterson29060642009-01-31 22:14:21 +00009987 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009989 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990 return NULL;
9991}
9992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009993#define FILL(kind, data, value, start, length) \
9994 do { \
9995 Py_ssize_t i_ = 0; \
9996 assert(kind != PyUnicode_WCHAR_KIND); \
9997 switch ((kind)) { \
9998 case PyUnicode_1BYTE_KIND: { \
9999 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010000 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001 break; \
10002 } \
10003 case PyUnicode_2BYTE_KIND: { \
10004 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10005 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10006 break; \
10007 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010008 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10010 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10011 break; \
10012 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010013 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 } \
10015 } while (0)
10016
Victor Stinnerd3f08822012-05-29 12:57:52 +020010017void
10018_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10019 Py_UCS4 fill_char)
10020{
10021 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10022 const void *data = PyUnicode_DATA(unicode);
10023 assert(PyUnicode_IS_READY(unicode));
10024 assert(unicode_modifiable(unicode));
10025 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10026 assert(start >= 0);
10027 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10028 FILL(kind, data, fill_char, start, length);
10029}
10030
Victor Stinner3fe55312012-01-04 00:33:50 +010010031Py_ssize_t
10032PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10033 Py_UCS4 fill_char)
10034{
10035 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010036
10037 if (!PyUnicode_Check(unicode)) {
10038 PyErr_BadInternalCall();
10039 return -1;
10040 }
10041 if (PyUnicode_READY(unicode) == -1)
10042 return -1;
10043 if (unicode_check_modifiable(unicode))
10044 return -1;
10045
Victor Stinnerd3f08822012-05-29 12:57:52 +020010046 if (start < 0) {
10047 PyErr_SetString(PyExc_IndexError, "string index out of range");
10048 return -1;
10049 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010050 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10051 PyErr_SetString(PyExc_ValueError,
10052 "fill character is bigger than "
10053 "the string maximum character");
10054 return -1;
10055 }
10056
10057 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10058 length = Py_MIN(maxlen, length);
10059 if (length <= 0)
10060 return 0;
10061
Victor Stinnerd3f08822012-05-29 12:57:52 +020010062 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010063 return length;
10064}
10065
Victor Stinner9310abb2011-10-05 00:59:23 +020010066static PyObject *
10067pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010068 Py_ssize_t left,
10069 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010071{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 PyObject *u;
10073 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010074 int kind;
10075 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010076
10077 if (left < 0)
10078 left = 0;
10079 if (right < 0)
10080 right = 0;
10081
Victor Stinnerc4b49542011-12-11 22:44:26 +010010082 if (left == 0 && right == 0)
10083 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10086 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010087 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10088 return NULL;
10089 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010091 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010093 if (!u)
10094 return NULL;
10095
10096 kind = PyUnicode_KIND(u);
10097 data = PyUnicode_DATA(u);
10098 if (left)
10099 FILL(kind, data, fill, 0, left);
10100 if (right)
10101 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010102 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010103 assert(_PyUnicode_CheckConsistency(u, 1));
10104 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010105}
10106
Alexander Belopolsky40018472011-02-26 01:02:56 +000010107PyObject *
10108PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010110 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010111
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010112 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010113 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010114
Benjamin Petersonead6b532011-12-20 17:23:42 -060010115 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010117 if (PyUnicode_IS_ASCII(string))
10118 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010119 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010120 PyUnicode_GET_LENGTH(string), keepends);
10121 else
10122 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010123 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010124 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010125 break;
10126 case PyUnicode_2BYTE_KIND:
10127 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010128 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 PyUnicode_GET_LENGTH(string), keepends);
10130 break;
10131 case PyUnicode_4BYTE_KIND:
10132 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010133 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 PyUnicode_GET_LENGTH(string), keepends);
10135 break;
10136 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010137 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010140}
10141
Alexander Belopolsky40018472011-02-26 01:02:56 +000010142static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010143split(PyObject *self,
10144 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010145 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010146{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010147 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 void *buf1, *buf2;
10149 Py_ssize_t len1, len2;
10150 PyObject* out;
10151
Guido van Rossumd57fd912000-03-10 22:53:23 +000010152 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010153 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010154
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 if (PyUnicode_READY(self) == -1)
10156 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010159 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010161 if (PyUnicode_IS_ASCII(self))
10162 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010163 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010164 PyUnicode_GET_LENGTH(self), maxcount
10165 );
10166 else
10167 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010168 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010169 PyUnicode_GET_LENGTH(self), maxcount
10170 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 case PyUnicode_2BYTE_KIND:
10172 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010173 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 PyUnicode_GET_LENGTH(self), maxcount
10175 );
10176 case PyUnicode_4BYTE_KIND:
10177 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010178 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 PyUnicode_GET_LENGTH(self), maxcount
10180 );
10181 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010182 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 }
10184
10185 if (PyUnicode_READY(substring) == -1)
10186 return NULL;
10187
10188 kind1 = PyUnicode_KIND(self);
10189 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 len1 = PyUnicode_GET_LENGTH(self);
10191 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010192 if (kind1 < kind2 || len1 < len2) {
10193 out = PyList_New(1);
10194 if (out == NULL)
10195 return NULL;
10196 Py_INCREF(self);
10197 PyList_SET_ITEM(out, 0, self);
10198 return out;
10199 }
10200 buf1 = PyUnicode_DATA(self);
10201 buf2 = PyUnicode_DATA(substring);
10202 if (kind2 != kind1) {
10203 buf2 = _PyUnicode_AsKind(substring, kind1);
10204 if (!buf2)
10205 return NULL;
10206 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010208 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010210 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10211 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010212 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010213 else
10214 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010215 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 break;
10217 case PyUnicode_2BYTE_KIND:
10218 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010219 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 break;
10221 case PyUnicode_4BYTE_KIND:
10222 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010223 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 break;
10225 default:
10226 out = NULL;
10227 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010228 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 PyMem_Free(buf2);
10230 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010231}
10232
Alexander Belopolsky40018472011-02-26 01:02:56 +000010233static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010234rsplit(PyObject *self,
10235 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010236 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010237{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010238 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 void *buf1, *buf2;
10240 Py_ssize_t len1, len2;
10241 PyObject* out;
10242
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010243 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010244 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 if (PyUnicode_READY(self) == -1)
10247 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010250 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010252 if (PyUnicode_IS_ASCII(self))
10253 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010254 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010255 PyUnicode_GET_LENGTH(self), maxcount
10256 );
10257 else
10258 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010259 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010260 PyUnicode_GET_LENGTH(self), maxcount
10261 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 case PyUnicode_2BYTE_KIND:
10263 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010264 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 PyUnicode_GET_LENGTH(self), maxcount
10266 );
10267 case PyUnicode_4BYTE_KIND:
10268 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010269 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 PyUnicode_GET_LENGTH(self), maxcount
10271 );
10272 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010273 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 }
10275
10276 if (PyUnicode_READY(substring) == -1)
10277 return NULL;
10278
10279 kind1 = PyUnicode_KIND(self);
10280 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 len1 = PyUnicode_GET_LENGTH(self);
10282 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010283 if (kind1 < kind2 || len1 < len2) {
10284 out = PyList_New(1);
10285 if (out == NULL)
10286 return NULL;
10287 Py_INCREF(self);
10288 PyList_SET_ITEM(out, 0, self);
10289 return out;
10290 }
10291 buf1 = PyUnicode_DATA(self);
10292 buf2 = PyUnicode_DATA(substring);
10293 if (kind2 != kind1) {
10294 buf2 = _PyUnicode_AsKind(substring, kind1);
10295 if (!buf2)
10296 return NULL;
10297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010299 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010301 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10302 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010303 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010304 else
10305 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010306 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 break;
10308 case PyUnicode_2BYTE_KIND:
10309 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010310 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 break;
10312 case PyUnicode_4BYTE_KIND:
10313 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010314 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 break;
10316 default:
10317 out = NULL;
10318 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010319 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 PyMem_Free(buf2);
10321 return out;
10322}
10323
10324static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010325anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10326 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010328 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010330 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10331 return asciilib_find(buf1, len1, buf2, len2, offset);
10332 else
10333 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 case PyUnicode_2BYTE_KIND:
10335 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10336 case PyUnicode_4BYTE_KIND:
10337 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10338 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010339 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340}
10341
10342static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010343anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10344 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010346 switch (kind) {
10347 case PyUnicode_1BYTE_KIND:
10348 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10349 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10350 else
10351 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10352 case PyUnicode_2BYTE_KIND:
10353 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10354 case PyUnicode_4BYTE_KIND:
10355 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10356 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010357 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010358}
10359
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010360static void
10361replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10362 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10363{
10364 int kind = PyUnicode_KIND(u);
10365 void *data = PyUnicode_DATA(u);
10366 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10367 if (kind == PyUnicode_1BYTE_KIND) {
10368 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10369 (Py_UCS1 *)data + len,
10370 u1, u2, maxcount);
10371 }
10372 else if (kind == PyUnicode_2BYTE_KIND) {
10373 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10374 (Py_UCS2 *)data + len,
10375 u1, u2, maxcount);
10376 }
10377 else {
10378 assert(kind == PyUnicode_4BYTE_KIND);
10379 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10380 (Py_UCS4 *)data + len,
10381 u1, u2, maxcount);
10382 }
10383}
10384
Alexander Belopolsky40018472011-02-26 01:02:56 +000010385static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386replace(PyObject *self, PyObject *str1,
10387 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010388{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 PyObject *u;
10390 char *sbuf = PyUnicode_DATA(self);
10391 char *buf1 = PyUnicode_DATA(str1);
10392 char *buf2 = PyUnicode_DATA(str2);
10393 int srelease = 0, release1 = 0, release2 = 0;
10394 int skind = PyUnicode_KIND(self);
10395 int kind1 = PyUnicode_KIND(str1);
10396 int kind2 = PyUnicode_KIND(str2);
10397 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10398 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10399 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010400 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010401 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010402
10403 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010404 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010406 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010407
Victor Stinner59de0ee2011-10-07 10:01:28 +020010408 if (str1 == str2)
10409 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410
Victor Stinner49a0a212011-10-12 23:46:10 +020010411 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010412 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10413 if (maxchar < maxchar_str1)
10414 /* substring too wide to be present */
10415 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010416 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10417 /* Replacing str1 with str2 may cause a maxchar reduction in the
10418 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010419 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010420 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010423 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010425 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010427 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010428 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010429 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010430
Victor Stinner69ed0f42013-04-09 21:48:24 +020010431 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010432 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010433 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010434 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010435 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010437 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010439
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010440 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10441 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010442 }
10443 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 int rkind = skind;
10445 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010446 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 if (kind1 < rkind) {
10449 /* widen substring */
10450 buf1 = _PyUnicode_AsKind(str1, rkind);
10451 if (!buf1) goto error;
10452 release1 = 1;
10453 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010454 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010455 if (i < 0)
10456 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 if (rkind > kind2) {
10458 /* widen replacement */
10459 buf2 = _PyUnicode_AsKind(str2, rkind);
10460 if (!buf2) goto error;
10461 release2 = 1;
10462 }
10463 else if (rkind < kind2) {
10464 /* widen self and buf1 */
10465 rkind = kind2;
10466 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010467 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 sbuf = _PyUnicode_AsKind(self, rkind);
10469 if (!sbuf) goto error;
10470 srelease = 1;
10471 buf1 = _PyUnicode_AsKind(str1, rkind);
10472 if (!buf1) goto error;
10473 release1 = 1;
10474 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010475 u = PyUnicode_New(slen, maxchar);
10476 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010478 assert(PyUnicode_KIND(u) == rkind);
10479 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010480
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010481 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010482 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010483 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010485 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010487
10488 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010489 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010490 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010491 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010492 if (i == -1)
10493 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010494 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010496 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010498 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010499 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010500 }
10501 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010503 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010504 int rkind = skind;
10505 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010506
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010507 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010508 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 buf1 = _PyUnicode_AsKind(str1, rkind);
10510 if (!buf1) goto error;
10511 release1 = 1;
10512 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010513 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010514 if (n == 0)
10515 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010517 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 buf2 = _PyUnicode_AsKind(str2, rkind);
10519 if (!buf2) goto error;
10520 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010521 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010523 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 rkind = kind2;
10525 sbuf = _PyUnicode_AsKind(self, rkind);
10526 if (!sbuf) goto error;
10527 srelease = 1;
10528 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010529 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 buf1 = _PyUnicode_AsKind(str1, rkind);
10531 if (!buf1) goto error;
10532 release1 = 1;
10533 }
10534 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10535 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010536 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 PyErr_SetString(PyExc_OverflowError,
10538 "replace string is too long");
10539 goto error;
10540 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010541 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010542 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010543 _Py_INCREF_UNICODE_EMPTY();
10544 if (!unicode_empty)
10545 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010546 u = unicode_empty;
10547 goto done;
10548 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010549 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 PyErr_SetString(PyExc_OverflowError,
10551 "replace string is too long");
10552 goto error;
10553 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010554 u = PyUnicode_New(new_size, maxchar);
10555 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010557 assert(PyUnicode_KIND(u) == rkind);
10558 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 ires = i = 0;
10560 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010561 while (n-- > 0) {
10562 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010563 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010564 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010565 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010566 if (j == -1)
10567 break;
10568 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010569 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010570 memcpy(res + rkind * ires,
10571 sbuf + rkind * i,
10572 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010574 }
10575 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010577 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010579 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010581 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010583 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010585 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010586 memcpy(res + rkind * ires,
10587 sbuf + rkind * i,
10588 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010589 }
10590 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010591 /* interleave */
10592 while (n > 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 if (--n <= 0)
10598 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010599 memcpy(res + rkind * ires,
10600 sbuf + rkind * i,
10601 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 ires++;
10603 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010604 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010605 memcpy(res + rkind * ires,
10606 sbuf + rkind * i,
10607 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010608 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010609 }
10610
10611 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010612 unicode_adjust_maxchar(&u);
10613 if (u == NULL)
10614 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010616
10617 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 if (srelease)
10619 PyMem_FREE(sbuf);
10620 if (release1)
10621 PyMem_FREE(buf1);
10622 if (release2)
10623 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010624 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010626
Benjamin Peterson29060642009-01-31 22:14:21 +000010627 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010628 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 if (srelease)
10630 PyMem_FREE(sbuf);
10631 if (release1)
10632 PyMem_FREE(buf1);
10633 if (release2)
10634 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010635 return unicode_result_unchanged(self);
10636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010637 error:
10638 if (srelease && sbuf)
10639 PyMem_FREE(sbuf);
10640 if (release1 && buf1)
10641 PyMem_FREE(buf1);
10642 if (release2 && buf2)
10643 PyMem_FREE(buf2);
10644 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010645}
10646
10647/* --- Unicode Object Methods --------------------------------------------- */
10648
INADA Naoki3ae20562017-01-16 20:41:20 +090010649/*[clinic input]
10650str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651
INADA Naoki3ae20562017-01-16 20:41:20 +090010652Return a version of the string where each word is titlecased.
10653
10654More specifically, words start with uppercased characters and all remaining
10655cased characters have lower case.
10656[clinic start generated code]*/
10657
10658static PyObject *
10659unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010660/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010662 if (PyUnicode_READY(self) == -1)
10663 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010664 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010665}
10666
INADA Naoki3ae20562017-01-16 20:41:20 +090010667/*[clinic input]
10668str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010669
INADA Naoki3ae20562017-01-16 20:41:20 +090010670Return a capitalized version of the string.
10671
10672More specifically, make the first character have upper case and the rest lower
10673case.
10674[clinic start generated code]*/
10675
10676static PyObject *
10677unicode_capitalize_impl(PyObject *self)
10678/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010679{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010680 if (PyUnicode_READY(self) == -1)
10681 return NULL;
10682 if (PyUnicode_GET_LENGTH(self) == 0)
10683 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010684 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685}
10686
INADA Naoki3ae20562017-01-16 20:41:20 +090010687/*[clinic input]
10688str.casefold as unicode_casefold
10689
10690Return a version of the string suitable for caseless comparisons.
10691[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010692
10693static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010694unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010695/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010696{
10697 if (PyUnicode_READY(self) == -1)
10698 return NULL;
10699 if (PyUnicode_IS_ASCII(self))
10700 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010701 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010702}
10703
10704
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010705/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010706
10707static int
10708convert_uc(PyObject *obj, void *addr)
10709{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010711
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010712 if (!PyUnicode_Check(obj)) {
10713 PyErr_Format(PyExc_TypeError,
10714 "The fill character must be a unicode character, "
10715 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010716 return 0;
10717 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010718 if (PyUnicode_READY(obj) < 0)
10719 return 0;
10720 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010721 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010722 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010723 return 0;
10724 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010725 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010726 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010727}
10728
INADA Naoki3ae20562017-01-16 20:41:20 +090010729/*[clinic input]
10730str.center as unicode_center
10731
10732 width: Py_ssize_t
10733 fillchar: Py_UCS4 = ' '
10734 /
10735
10736Return a centered string of length width.
10737
10738Padding is done using the specified fill character (default is a space).
10739[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010740
10741static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010742unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10743/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010745 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010746
Benjamin Petersonbac79492012-01-14 13:34:47 -050010747 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748 return NULL;
10749
Victor Stinnerc4b49542011-12-11 22:44:26 +010010750 if (PyUnicode_GET_LENGTH(self) >= width)
10751 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752
Victor Stinnerc4b49542011-12-11 22:44:26 +010010753 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010754 left = marg / 2 + (marg & width & 1);
10755
Victor Stinner9310abb2011-10-05 00:59:23 +020010756 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757}
10758
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010759/* This function assumes that str1 and str2 are readied by the caller. */
10760
Marc-André Lemburge5034372000-08-08 08:04:29 +000010761static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010762unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010763{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010764#define COMPARE(TYPE1, TYPE2) \
10765 do { \
10766 TYPE1* p1 = (TYPE1 *)data1; \
10767 TYPE2* p2 = (TYPE2 *)data2; \
10768 TYPE1* end = p1 + len; \
10769 Py_UCS4 c1, c2; \
10770 for (; p1 != end; p1++, p2++) { \
10771 c1 = *p1; \
10772 c2 = *p2; \
10773 if (c1 != c2) \
10774 return (c1 < c2) ? -1 : 1; \
10775 } \
10776 } \
10777 while (0)
10778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 int kind1, kind2;
10780 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010781 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 kind1 = PyUnicode_KIND(str1);
10784 kind2 = PyUnicode_KIND(str2);
10785 data1 = PyUnicode_DATA(str1);
10786 data2 = PyUnicode_DATA(str2);
10787 len1 = PyUnicode_GET_LENGTH(str1);
10788 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010789 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010790
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010791 switch(kind1) {
10792 case PyUnicode_1BYTE_KIND:
10793 {
10794 switch(kind2) {
10795 case PyUnicode_1BYTE_KIND:
10796 {
10797 int cmp = memcmp(data1, data2, len);
10798 /* normalize result of memcmp() into the range [-1; 1] */
10799 if (cmp < 0)
10800 return -1;
10801 if (cmp > 0)
10802 return 1;
10803 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010804 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010805 case PyUnicode_2BYTE_KIND:
10806 COMPARE(Py_UCS1, Py_UCS2);
10807 break;
10808 case PyUnicode_4BYTE_KIND:
10809 COMPARE(Py_UCS1, Py_UCS4);
10810 break;
10811 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010812 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010813 }
10814 break;
10815 }
10816 case PyUnicode_2BYTE_KIND:
10817 {
10818 switch(kind2) {
10819 case PyUnicode_1BYTE_KIND:
10820 COMPARE(Py_UCS2, Py_UCS1);
10821 break;
10822 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010823 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010824 COMPARE(Py_UCS2, Py_UCS2);
10825 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010826 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010827 case PyUnicode_4BYTE_KIND:
10828 COMPARE(Py_UCS2, Py_UCS4);
10829 break;
10830 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010831 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010832 }
10833 break;
10834 }
10835 case PyUnicode_4BYTE_KIND:
10836 {
10837 switch(kind2) {
10838 case PyUnicode_1BYTE_KIND:
10839 COMPARE(Py_UCS4, Py_UCS1);
10840 break;
10841 case PyUnicode_2BYTE_KIND:
10842 COMPARE(Py_UCS4, Py_UCS2);
10843 break;
10844 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010845 {
10846#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10847 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10848 /* normalize result of wmemcmp() into the range [-1; 1] */
10849 if (cmp < 0)
10850 return -1;
10851 if (cmp > 0)
10852 return 1;
10853#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010854 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010855#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010856 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010857 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010858 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010859 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010860 }
10861 break;
10862 }
10863 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010864 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010865 }
10866
Victor Stinner770e19e2012-10-04 22:59:45 +020010867 if (len1 == len2)
10868 return 0;
10869 if (len1 < len2)
10870 return -1;
10871 else
10872 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010873
10874#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010875}
10876
Benjamin Peterson621b4302016-09-09 13:54:34 -070010877static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010878unicode_compare_eq(PyObject *str1, PyObject *str2)
10879{
10880 int kind;
10881 void *data1, *data2;
10882 Py_ssize_t len;
10883 int cmp;
10884
Victor Stinnere5567ad2012-10-23 02:48:49 +020010885 len = PyUnicode_GET_LENGTH(str1);
10886 if (PyUnicode_GET_LENGTH(str2) != len)
10887 return 0;
10888 kind = PyUnicode_KIND(str1);
10889 if (PyUnicode_KIND(str2) != kind)
10890 return 0;
10891 data1 = PyUnicode_DATA(str1);
10892 data2 = PyUnicode_DATA(str2);
10893
10894 cmp = memcmp(data1, data2, len * kind);
10895 return (cmp == 0);
10896}
10897
10898
Alexander Belopolsky40018472011-02-26 01:02:56 +000010899int
10900PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010902 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10903 if (PyUnicode_READY(left) == -1 ||
10904 PyUnicode_READY(right) == -1)
10905 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010906
10907 /* a string is equal to itself */
10908 if (left == right)
10909 return 0;
10910
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010911 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010912 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010913 PyErr_Format(PyExc_TypeError,
10914 "Can't compare %.100s and %.100s",
10915 left->ob_type->tp_name,
10916 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917 return -1;
10918}
10919
Martin v. Löwis5b222132007-06-10 09:51:05 +000010920int
10921PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10922{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010923 Py_ssize_t i;
10924 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010925 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010926 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927
Victor Stinner910337b2011-10-03 03:20:16 +020010928 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010929 if (!PyUnicode_IS_READY(uni)) {
10930 const wchar_t *ws = _PyUnicode_WSTR(uni);
10931 /* Compare Unicode string and source character set string */
10932 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10933 if (chr != ustr[i])
10934 return (chr < ustr[i]) ? -1 : 1;
10935 }
10936 /* This check keeps Python strings that end in '\0' from comparing equal
10937 to C strings identical up to that point. */
10938 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10939 return 1; /* uni is longer */
10940 if (ustr[i])
10941 return -1; /* str is longer */
10942 return 0;
10943 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010944 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010945 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010946 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010947 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010948 size_t len, len2 = strlen(str);
10949 int cmp;
10950
10951 len = Py_MIN(len1, len2);
10952 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010953 if (cmp != 0) {
10954 if (cmp < 0)
10955 return -1;
10956 else
10957 return 1;
10958 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010959 if (len1 > len2)
10960 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010961 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010962 return -1; /* str is longer */
10963 return 0;
10964 }
10965 else {
10966 void *data = PyUnicode_DATA(uni);
10967 /* Compare Unicode string and source character set string */
10968 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010969 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010970 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10971 /* This check keeps Python strings that end in '\0' from comparing equal
10972 to C strings identical up to that point. */
10973 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10974 return 1; /* uni is longer */
10975 if (str[i])
10976 return -1; /* str is longer */
10977 return 0;
10978 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010979}
10980
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010981static int
10982non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
10983{
10984 size_t i, len;
10985 const wchar_t *p;
10986 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
10987 if (strlen(str) != len)
10988 return 0;
10989 p = _PyUnicode_WSTR(unicode);
10990 assert(p);
10991 for (i = 0; i < len; i++) {
10992 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020010993 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010994 return 0;
10995 }
10996 return 1;
10997}
10998
10999int
11000_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11001{
11002 size_t len;
11003 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011004 assert(str);
11005#ifndef NDEBUG
11006 for (const char *p = str; *p; p++) {
11007 assert((unsigned char)*p < 128);
11008 }
11009#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011010 if (PyUnicode_READY(unicode) == -1) {
11011 /* Memory error or bad data */
11012 PyErr_Clear();
11013 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11014 }
11015 if (!PyUnicode_IS_ASCII(unicode))
11016 return 0;
11017 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11018 return strlen(str) == len &&
11019 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11020}
11021
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011022int
11023_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11024{
11025 PyObject *right_uni;
11026 Py_hash_t hash;
11027
11028 assert(_PyUnicode_CHECK(left));
11029 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011030#ifndef NDEBUG
11031 for (const char *p = right->string; *p; p++) {
11032 assert((unsigned char)*p < 128);
11033 }
11034#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011035
11036 if (PyUnicode_READY(left) == -1) {
11037 /* memory error or bad data */
11038 PyErr_Clear();
11039 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11040 }
11041
11042 if (!PyUnicode_IS_ASCII(left))
11043 return 0;
11044
11045 right_uni = _PyUnicode_FromId(right); /* borrowed */
11046 if (right_uni == NULL) {
11047 /* memory error or bad data */
11048 PyErr_Clear();
11049 return _PyUnicode_EqualToASCIIString(left, right->string);
11050 }
11051
11052 if (left == right_uni)
11053 return 1;
11054
11055 if (PyUnicode_CHECK_INTERNED(left))
11056 return 0;
11057
INADA Naoki7cc95f52018-01-28 02:07:09 +090011058 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011059 hash = _PyUnicode_HASH(left);
11060 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11061 return 0;
11062
11063 return unicode_compare_eq(left, right_uni);
11064}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011065
Alexander Belopolsky40018472011-02-26 01:02:56 +000011066PyObject *
11067PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011068{
11069 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011070
Victor Stinnere5567ad2012-10-23 02:48:49 +020011071 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11072 Py_RETURN_NOTIMPLEMENTED;
11073
11074 if (PyUnicode_READY(left) == -1 ||
11075 PyUnicode_READY(right) == -1)
11076 return NULL;
11077
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011078 if (left == right) {
11079 switch (op) {
11080 case Py_EQ:
11081 case Py_LE:
11082 case Py_GE:
11083 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011084 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011085 case Py_NE:
11086 case Py_LT:
11087 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011088 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011089 default:
11090 PyErr_BadArgument();
11091 return NULL;
11092 }
11093 }
11094 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011095 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011096 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011097 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011098 }
11099 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011100 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011101 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011102 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011103}
11104
Alexander Belopolsky40018472011-02-26 01:02:56 +000011105int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011106_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11107{
11108 return unicode_eq(aa, bb);
11109}
11110
11111int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011112PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011113{
Victor Stinner77282cb2013-04-14 19:22:47 +020011114 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011115 void *buf1, *buf2;
11116 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011117 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011118
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011119 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011120 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011121 "'in <string>' requires string as left operand, not %.100s",
11122 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011123 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011124 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011125 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011126 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011127 if (ensure_unicode(str) < 0)
11128 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011130 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011131 kind2 = PyUnicode_KIND(substr);
11132 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011133 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011135 len2 = PyUnicode_GET_LENGTH(substr);
11136 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011137 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011138 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011139 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011140 if (len2 == 1) {
11141 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11142 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011143 return result;
11144 }
11145 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011146 buf2 = _PyUnicode_AsKind(substr, kind1);
11147 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011148 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011149 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150
Victor Stinner77282cb2013-04-14 19:22:47 +020011151 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011152 case PyUnicode_1BYTE_KIND:
11153 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11154 break;
11155 case PyUnicode_2BYTE_KIND:
11156 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11157 break;
11158 case PyUnicode_4BYTE_KIND:
11159 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11160 break;
11161 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011162 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011163 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011164
Victor Stinner77282cb2013-04-14 19:22:47 +020011165 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166 PyMem_Free(buf2);
11167
Guido van Rossum403d68b2000-03-13 15:55:09 +000011168 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011169}
11170
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171/* Concat to string or Unicode object giving a new Unicode object. */
11172
Alexander Belopolsky40018472011-02-26 01:02:56 +000011173PyObject *
11174PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011176 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011177 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011178 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011180 if (ensure_unicode(left) < 0)
11181 return NULL;
11182
11183 if (!PyUnicode_Check(right)) {
11184 PyErr_Format(PyExc_TypeError,
11185 "can only concatenate str (not \"%.200s\") to str",
11186 right->ob_type->tp_name);
11187 return NULL;
11188 }
11189 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011190 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191
11192 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011193 if (left == unicode_empty)
11194 return PyUnicode_FromObject(right);
11195 if (right == unicode_empty)
11196 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011198 left_len = PyUnicode_GET_LENGTH(left);
11199 right_len = PyUnicode_GET_LENGTH(right);
11200 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011201 PyErr_SetString(PyExc_OverflowError,
11202 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011203 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011204 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011205 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011206
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011207 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11208 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011209 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011210
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011212 result = PyUnicode_New(new_len, maxchar);
11213 if (result == NULL)
11214 return NULL;
11215 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11216 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11217 assert(_PyUnicode_CheckConsistency(result, 1));
11218 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219}
11220
Walter Dörwald1ab83302007-05-18 17:15:44 +000011221void
Victor Stinner23e56682011-10-03 03:54:37 +020011222PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011223{
Victor Stinner23e56682011-10-03 03:54:37 +020011224 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011225 Py_UCS4 maxchar, maxchar2;
11226 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011227
11228 if (p_left == NULL) {
11229 if (!PyErr_Occurred())
11230 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011231 return;
11232 }
Victor Stinner23e56682011-10-03 03:54:37 +020011233 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011234 if (right == NULL || left == NULL
11235 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011236 if (!PyErr_Occurred())
11237 PyErr_BadInternalCall();
11238 goto error;
11239 }
11240
Benjamin Petersonbac79492012-01-14 13:34:47 -050011241 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011242 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011243 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011244 goto error;
11245
Victor Stinner488fa492011-12-12 00:01:39 +010011246 /* Shortcuts */
11247 if (left == unicode_empty) {
11248 Py_DECREF(left);
11249 Py_INCREF(right);
11250 *p_left = right;
11251 return;
11252 }
11253 if (right == unicode_empty)
11254 return;
11255
11256 left_len = PyUnicode_GET_LENGTH(left);
11257 right_len = PyUnicode_GET_LENGTH(right);
11258 if (left_len > PY_SSIZE_T_MAX - right_len) {
11259 PyErr_SetString(PyExc_OverflowError,
11260 "strings are too large to concat");
11261 goto error;
11262 }
11263 new_len = left_len + right_len;
11264
11265 if (unicode_modifiable(left)
11266 && PyUnicode_CheckExact(right)
11267 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011268 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11269 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011270 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011271 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011272 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11273 {
11274 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011275 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011276 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011277
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011278 /* copy 'right' into the newly allocated area of 'left' */
11279 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011280 }
Victor Stinner488fa492011-12-12 00:01:39 +010011281 else {
11282 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11283 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011284 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011285
Victor Stinner488fa492011-12-12 00:01:39 +010011286 /* Concat the two Unicode strings */
11287 res = PyUnicode_New(new_len, maxchar);
11288 if (res == NULL)
11289 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011290 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11291 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011292 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011293 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011294 }
11295 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011296 return;
11297
11298error:
Victor Stinner488fa492011-12-12 00:01:39 +010011299 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011300}
11301
11302void
11303PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11304{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011305 PyUnicode_Append(pleft, right);
11306 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011307}
11308
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011309/*
11310Wraps stringlib_parse_args_finds() and additionally ensures that the
11311first argument is a unicode object.
11312*/
11313
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011314static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011315parse_args_finds_unicode(const char * function_name, PyObject *args,
11316 PyObject **substring,
11317 Py_ssize_t *start, Py_ssize_t *end)
11318{
11319 if(stringlib_parse_args_finds(function_name, args, substring,
11320 start, end)) {
11321 if (ensure_unicode(*substring) < 0)
11322 return 0;
11323 return 1;
11324 }
11325 return 0;
11326}
11327
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011328PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011329 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011331Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011332string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011333interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334
11335static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011336unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011338 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011339 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011340 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011342 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011343 void *buf1, *buf2;
11344 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011346 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011347 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 kind1 = PyUnicode_KIND(self);
11350 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011351 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011352 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011353
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011354 len1 = PyUnicode_GET_LENGTH(self);
11355 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011357 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011358 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011359
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011360 buf1 = PyUnicode_DATA(self);
11361 buf2 = PyUnicode_DATA(substring);
11362 if (kind2 != kind1) {
11363 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011364 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011365 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011366 }
11367 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 case PyUnicode_1BYTE_KIND:
11369 iresult = ucs1lib_count(
11370 ((Py_UCS1*)buf1) + start, end - start,
11371 buf2, len2, PY_SSIZE_T_MAX
11372 );
11373 break;
11374 case PyUnicode_2BYTE_KIND:
11375 iresult = ucs2lib_count(
11376 ((Py_UCS2*)buf1) + start, end - start,
11377 buf2, len2, PY_SSIZE_T_MAX
11378 );
11379 break;
11380 case PyUnicode_4BYTE_KIND:
11381 iresult = ucs4lib_count(
11382 ((Py_UCS4*)buf1) + start, end - start,
11383 buf2, len2, PY_SSIZE_T_MAX
11384 );
11385 break;
11386 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011387 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011388 }
11389
11390 result = PyLong_FromSsize_t(iresult);
11391
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011392 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395 return result;
11396}
11397
INADA Naoki3ae20562017-01-16 20:41:20 +090011398/*[clinic input]
11399str.encode as unicode_encode
11400
11401 encoding: str(c_default="NULL") = 'utf-8'
11402 The encoding in which to encode the string.
11403 errors: str(c_default="NULL") = 'strict'
11404 The error handling scheme to use for encoding errors.
11405 The default is 'strict' meaning that encoding errors raise a
11406 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11407 'xmlcharrefreplace' as well as any other name registered with
11408 codecs.register_error that can handle UnicodeEncodeErrors.
11409
11410Encode the string using the codec registered for encoding.
11411[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412
11413static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011414unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011415/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011417 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011418}
11419
INADA Naoki3ae20562017-01-16 20:41:20 +090011420/*[clinic input]
11421str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422
INADA Naoki3ae20562017-01-16 20:41:20 +090011423 tabsize: int = 8
11424
11425Return a copy where all tab characters are expanded using spaces.
11426
11427If tabsize is not given, a tab size of 8 characters is assumed.
11428[clinic start generated code]*/
11429
11430static PyObject *
11431unicode_expandtabs_impl(PyObject *self, int tabsize)
11432/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011434 Py_ssize_t i, j, line_pos, src_len, incr;
11435 Py_UCS4 ch;
11436 PyObject *u;
11437 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011438 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011439 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440
Antoine Pitrou22425222011-10-04 19:10:51 +020011441 if (PyUnicode_READY(self) == -1)
11442 return NULL;
11443
Thomas Wouters7e474022000-07-16 12:04:32 +000011444 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011445 src_len = PyUnicode_GET_LENGTH(self);
11446 i = j = line_pos = 0;
11447 kind = PyUnicode_KIND(self);
11448 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011449 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 for (; i < src_len; i++) {
11451 ch = PyUnicode_READ(kind, src_data, i);
11452 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011453 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011455 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011457 goto overflow;
11458 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011459 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011460 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011461 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011463 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011464 goto overflow;
11465 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011467 if (ch == '\n' || ch == '\r')
11468 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011470 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011471 if (!found)
11472 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011473
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011475 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011476 if (!u)
11477 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011478 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479
Antoine Pitroue71d5742011-10-04 15:55:09 +020011480 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481
Antoine Pitroue71d5742011-10-04 15:55:09 +020011482 for (; i < src_len; i++) {
11483 ch = PyUnicode_READ(kind, src_data, i);
11484 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 incr = tabsize - (line_pos % tabsize);
11487 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011488 FILL(kind, dest_data, ' ', j, incr);
11489 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011490 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011491 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011492 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011493 line_pos++;
11494 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011495 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011496 if (ch == '\n' || ch == '\r')
11497 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011499 }
11500 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011501 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011502
Antoine Pitroue71d5742011-10-04 15:55:09 +020011503 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011504 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11505 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506}
11507
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011508PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011509 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510\n\
11511Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011512such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513arguments start and end are interpreted as in slice notation.\n\
11514\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011515Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516
11517static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011520 /* initialize variables to prevent gcc warning */
11521 PyObject *substring = NULL;
11522 Py_ssize_t start = 0;
11523 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011524 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011526 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011529 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011531
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011532 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011533
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 if (result == -2)
11535 return NULL;
11536
Christian Heimes217cfd12007-12-02 14:31:20 +000011537 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538}
11539
11540static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011541unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011543 void *data;
11544 enum PyUnicode_Kind kind;
11545 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011546
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011547 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011548 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011550 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011551 if (PyUnicode_READY(self) == -1) {
11552 return NULL;
11553 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011554 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11555 PyErr_SetString(PyExc_IndexError, "string index out of range");
11556 return NULL;
11557 }
11558 kind = PyUnicode_KIND(self);
11559 data = PyUnicode_DATA(self);
11560 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011561 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562}
11563
Guido van Rossumc2504932007-09-18 19:42:40 +000011564/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011565 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011566static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011567unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568{
Guido van Rossumc2504932007-09-18 19:42:40 +000011569 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011570 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011571
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011572#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011573 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011574#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 if (_PyUnicode_HASH(self) != -1)
11576 return _PyUnicode_HASH(self);
11577 if (PyUnicode_READY(self) == -1)
11578 return -1;
11579 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011580 /*
11581 We make the hash of the empty string be 0, rather than using
11582 (prefix ^ suffix), since this slightly obfuscates the hash secret
11583 */
11584 if (len == 0) {
11585 _PyUnicode_HASH(self) = 0;
11586 return 0;
11587 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011588 x = _Py_HashBytes(PyUnicode_DATA(self),
11589 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011591 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592}
11593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011594PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596\n\
oldkaa0735f2018-02-02 16:52:55 +080011597Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011598such that sub is contained within S[start:end]. Optional\n\
11599arguments start and end are interpreted as in slice notation.\n\
11600\n\
11601Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602
11603static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011606 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011607 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011608 PyObject *substring = NULL;
11609 Py_ssize_t start = 0;
11610 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011612 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011615 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011618 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 if (result == -2)
11621 return NULL;
11622
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623 if (result < 0) {
11624 PyErr_SetString(PyExc_ValueError, "substring not found");
11625 return NULL;
11626 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011627
Christian Heimes217cfd12007-12-02 14:31:20 +000011628 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629}
11630
INADA Naoki3ae20562017-01-16 20:41:20 +090011631/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011632str.isascii as unicode_isascii
11633
11634Return True if all characters in the string are ASCII, False otherwise.
11635
11636ASCII characters have code points in the range U+0000-U+007F.
11637Empty string is ASCII too.
11638[clinic start generated code]*/
11639
11640static PyObject *
11641unicode_isascii_impl(PyObject *self)
11642/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11643{
11644 if (PyUnicode_READY(self) == -1) {
11645 return NULL;
11646 }
11647 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11648}
11649
11650/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011651str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011652
INADA Naoki3ae20562017-01-16 20:41:20 +090011653Return True if the string is a lowercase string, False otherwise.
11654
11655A string is lowercase if all cased characters in the string are lowercase and
11656there is at least one cased character in the string.
11657[clinic start generated code]*/
11658
11659static PyObject *
11660unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011661/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663 Py_ssize_t i, length;
11664 int kind;
11665 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666 int cased;
11667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011668 if (PyUnicode_READY(self) == -1)
11669 return NULL;
11670 length = PyUnicode_GET_LENGTH(self);
11671 kind = PyUnicode_KIND(self);
11672 data = PyUnicode_DATA(self);
11673
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 if (length == 1)
11676 return PyBool_FromLong(
11677 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011679 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011681 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011682
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 for (i = 0; i < length; i++) {
11685 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011686
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011688 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011689 else if (!cased && Py_UNICODE_ISLOWER(ch))
11690 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011692 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693}
11694
INADA Naoki3ae20562017-01-16 20:41:20 +090011695/*[clinic input]
11696str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697
INADA Naoki3ae20562017-01-16 20:41:20 +090011698Return True if the string is an uppercase string, False otherwise.
11699
11700A string is uppercase if all cased characters in the string are uppercase and
11701there is at least one cased character in the string.
11702[clinic start generated code]*/
11703
11704static PyObject *
11705unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011706/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708 Py_ssize_t i, length;
11709 int kind;
11710 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711 int cased;
11712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 if (PyUnicode_READY(self) == -1)
11714 return NULL;
11715 length = PyUnicode_GET_LENGTH(self);
11716 kind = PyUnicode_KIND(self);
11717 data = PyUnicode_DATA(self);
11718
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720 if (length == 1)
11721 return PyBool_FromLong(
11722 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011724 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011726 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011727
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 for (i = 0; i < length; i++) {
11730 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011731
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011733 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 else if (!cased && Py_UNICODE_ISUPPER(ch))
11735 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011737 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738}
11739
INADA Naoki3ae20562017-01-16 20:41:20 +090011740/*[clinic input]
11741str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742
INADA Naoki3ae20562017-01-16 20:41:20 +090011743Return True if the string is a title-cased string, False otherwise.
11744
11745In a title-cased string, upper- and title-case characters may only
11746follow uncased characters and lowercase characters only cased ones.
11747[clinic start generated code]*/
11748
11749static PyObject *
11750unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011751/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011753 Py_ssize_t i, length;
11754 int kind;
11755 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756 int cased, previous_is_cased;
11757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758 if (PyUnicode_READY(self) == -1)
11759 return NULL;
11760 length = PyUnicode_GET_LENGTH(self);
11761 kind = PyUnicode_KIND(self);
11762 data = PyUnicode_DATA(self);
11763
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 if (length == 1) {
11766 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11767 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11768 (Py_UNICODE_ISUPPER(ch) != 0));
11769 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011771 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011773 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011774
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775 cased = 0;
11776 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 for (i = 0; i < length; i++) {
11778 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011779
Benjamin Peterson29060642009-01-31 22:14:21 +000011780 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11781 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011782 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011783 previous_is_cased = 1;
11784 cased = 1;
11785 }
11786 else if (Py_UNICODE_ISLOWER(ch)) {
11787 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011788 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011789 previous_is_cased = 1;
11790 cased = 1;
11791 }
11792 else
11793 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011795 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796}
11797
INADA Naoki3ae20562017-01-16 20:41:20 +090011798/*[clinic input]
11799str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800
INADA Naoki3ae20562017-01-16 20:41:20 +090011801Return True if the string is a whitespace string, False otherwise.
11802
11803A string is whitespace if all characters in the string are whitespace and there
11804is at least one character in the string.
11805[clinic start generated code]*/
11806
11807static PyObject *
11808unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011809/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 Py_ssize_t i, length;
11812 int kind;
11813 void *data;
11814
11815 if (PyUnicode_READY(self) == -1)
11816 return NULL;
11817 length = PyUnicode_GET_LENGTH(self);
11818 kind = PyUnicode_KIND(self);
11819 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 if (length == 1)
11823 return PyBool_FromLong(
11824 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011826 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011828 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 for (i = 0; i < length; i++) {
11831 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011832 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011833 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011835 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836}
11837
INADA Naoki3ae20562017-01-16 20:41:20 +090011838/*[clinic input]
11839str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011840
INADA Naoki3ae20562017-01-16 20:41:20 +090011841Return True if the string is an alphabetic string, False otherwise.
11842
11843A string is alphabetic if all characters in the string are alphabetic and there
11844is at least one character in the string.
11845[clinic start generated code]*/
11846
11847static PyObject *
11848unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011849/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 Py_ssize_t i, length;
11852 int kind;
11853 void *data;
11854
11855 if (PyUnicode_READY(self) == -1)
11856 return NULL;
11857 length = PyUnicode_GET_LENGTH(self);
11858 kind = PyUnicode_KIND(self);
11859 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011860
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011861 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 if (length == 1)
11863 return PyBool_FromLong(
11864 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011865
11866 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011868 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 for (i = 0; i < length; i++) {
11871 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011872 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011873 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011874 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011875}
11876
INADA Naoki3ae20562017-01-16 20:41:20 +090011877/*[clinic input]
11878str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011879
INADA Naoki3ae20562017-01-16 20:41:20 +090011880Return True if the string is an alpha-numeric string, False otherwise.
11881
11882A string is alpha-numeric if all characters in the string are alpha-numeric and
11883there is at least one character in the string.
11884[clinic start generated code]*/
11885
11886static PyObject *
11887unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011888/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011889{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 int kind;
11891 void *data;
11892 Py_ssize_t len, i;
11893
11894 if (PyUnicode_READY(self) == -1)
11895 return NULL;
11896
11897 kind = PyUnicode_KIND(self);
11898 data = PyUnicode_DATA(self);
11899 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011900
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011901 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011902 if (len == 1) {
11903 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11904 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11905 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011906
11907 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011909 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 for (i = 0; i < len; i++) {
11912 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011913 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011914 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011915 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011916 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011917}
11918
INADA Naoki3ae20562017-01-16 20:41:20 +090011919/*[clinic input]
11920str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921
INADA Naoki3ae20562017-01-16 20:41:20 +090011922Return True if the string is a decimal string, False otherwise.
11923
11924A string is a decimal string if all characters in the string are decimal and
11925there is at least one character in the string.
11926[clinic start generated code]*/
11927
11928static PyObject *
11929unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011930/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011932 Py_ssize_t i, length;
11933 int kind;
11934 void *data;
11935
11936 if (PyUnicode_READY(self) == -1)
11937 return NULL;
11938 length = PyUnicode_GET_LENGTH(self);
11939 kind = PyUnicode_KIND(self);
11940 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943 if (length == 1)
11944 return PyBool_FromLong(
11945 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011946
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011947 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011949 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011950
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 for (i = 0; i < length; i++) {
11952 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011953 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011955 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956}
11957
INADA Naoki3ae20562017-01-16 20:41:20 +090011958/*[clinic input]
11959str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960
INADA Naoki3ae20562017-01-16 20:41:20 +090011961Return True if the string is a digit string, False otherwise.
11962
11963A string is a digit string if all characters in the string are digits and there
11964is at least one character in the string.
11965[clinic start generated code]*/
11966
11967static PyObject *
11968unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011969/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 Py_ssize_t i, length;
11972 int kind;
11973 void *data;
11974
11975 if (PyUnicode_READY(self) == -1)
11976 return NULL;
11977 length = PyUnicode_GET_LENGTH(self);
11978 kind = PyUnicode_KIND(self);
11979 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980
Guido van Rossumd57fd912000-03-10 22:53:23 +000011981 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011982 if (length == 1) {
11983 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11984 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11985 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011986
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011987 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011989 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011990
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991 for (i = 0; i < length; i++) {
11992 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011993 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011995 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011996}
11997
INADA Naoki3ae20562017-01-16 20:41:20 +090011998/*[clinic input]
11999str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012000
INADA Naoki3ae20562017-01-16 20:41:20 +090012001Return True if the string is a numeric string, False otherwise.
12002
12003A string is numeric if all characters in the string are numeric and there is at
12004least one character in the string.
12005[clinic start generated code]*/
12006
12007static PyObject *
12008unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012009/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012010{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 Py_ssize_t i, length;
12012 int kind;
12013 void *data;
12014
12015 if (PyUnicode_READY(self) == -1)
12016 return NULL;
12017 length = PyUnicode_GET_LENGTH(self);
12018 kind = PyUnicode_KIND(self);
12019 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012020
Guido van Rossumd57fd912000-03-10 22:53:23 +000012021 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 if (length == 1)
12023 return PyBool_FromLong(
12024 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012025
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012026 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012027 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012028 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012029
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030 for (i = 0; i < length; i++) {
12031 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012032 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012034 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012035}
12036
Martin v. Löwis47383402007-08-15 07:32:56 +000012037int
12038PyUnicode_IsIdentifier(PyObject *self)
12039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 int kind;
12041 void *data;
12042 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012043 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 if (PyUnicode_READY(self) == -1) {
12046 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012047 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012048 }
12049
12050 /* Special case for empty strings */
12051 if (PyUnicode_GET_LENGTH(self) == 0)
12052 return 0;
12053 kind = PyUnicode_KIND(self);
12054 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012055
12056 /* PEP 3131 says that the first character must be in
12057 XID_Start and subsequent characters in XID_Continue,
12058 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012059 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012060 letters, digits, underscore). However, given the current
12061 definition of XID_Start and XID_Continue, it is sufficient
12062 to check just for these, except that _ must be allowed
12063 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012064 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012065 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012066 return 0;
12067
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012068 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012070 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012071 return 1;
12072}
12073
INADA Naoki3ae20562017-01-16 20:41:20 +090012074/*[clinic input]
12075str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012076
INADA Naoki3ae20562017-01-16 20:41:20 +090012077Return True if the string is a valid Python identifier, False otherwise.
12078
12079Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12080"class".
12081[clinic start generated code]*/
12082
12083static PyObject *
12084unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012085/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012086{
12087 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12088}
12089
INADA Naoki3ae20562017-01-16 20:41:20 +090012090/*[clinic input]
12091str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012092
INADA Naoki3ae20562017-01-16 20:41:20 +090012093Return True if the string is printable, False otherwise.
12094
12095A string is printable if all of its characters are considered printable in
12096repr() or if it is empty.
12097[clinic start generated code]*/
12098
12099static PyObject *
12100unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012101/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012102{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012103 Py_ssize_t i, length;
12104 int kind;
12105 void *data;
12106
12107 if (PyUnicode_READY(self) == -1)
12108 return NULL;
12109 length = PyUnicode_GET_LENGTH(self);
12110 kind = PyUnicode_KIND(self);
12111 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012112
12113 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 if (length == 1)
12115 return PyBool_FromLong(
12116 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012118 for (i = 0; i < length; i++) {
12119 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012120 Py_RETURN_FALSE;
12121 }
12122 }
12123 Py_RETURN_TRUE;
12124}
12125
INADA Naoki3ae20562017-01-16 20:41:20 +090012126/*[clinic input]
12127str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128
INADA Naoki3ae20562017-01-16 20:41:20 +090012129 iterable: object
12130 /
12131
12132Concatenate any number of strings.
12133
Martin Panter91a88662017-01-24 00:30:06 +000012134The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012135The result is returned as a new string.
12136
12137Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12138[clinic start generated code]*/
12139
12140static PyObject *
12141unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012142/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143{
INADA Naoki3ae20562017-01-16 20:41:20 +090012144 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145}
12146
Martin v. Löwis18e16552006-02-15 17:27:45 +000012147static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012148unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012149{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012150 if (PyUnicode_READY(self) == -1)
12151 return -1;
12152 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153}
12154
INADA Naoki3ae20562017-01-16 20:41:20 +090012155/*[clinic input]
12156str.ljust as unicode_ljust
12157
12158 width: Py_ssize_t
12159 fillchar: Py_UCS4 = ' '
12160 /
12161
12162Return a left-justified string of length width.
12163
12164Padding is done using the specified fill character (default is a space).
12165[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166
12167static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012168unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12169/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012171 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012172 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173
Victor Stinnerc4b49542011-12-11 22:44:26 +010012174 if (PyUnicode_GET_LENGTH(self) >= width)
12175 return unicode_result_unchanged(self);
12176
12177 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178}
12179
INADA Naoki3ae20562017-01-16 20:41:20 +090012180/*[clinic input]
12181str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182
INADA Naoki3ae20562017-01-16 20:41:20 +090012183Return a copy of the string converted to lowercase.
12184[clinic start generated code]*/
12185
12186static PyObject *
12187unicode_lower_impl(PyObject *self)
12188/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012190 if (PyUnicode_READY(self) == -1)
12191 return NULL;
12192 if (PyUnicode_IS_ASCII(self))
12193 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012194 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195}
12196
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012197#define LEFTSTRIP 0
12198#define RIGHTSTRIP 1
12199#define BOTHSTRIP 2
12200
12201/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012202static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012203
INADA Naoki3ae20562017-01-16 20:41:20 +090012204#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012205
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012206/* externally visible for str.strip(unicode) */
12207PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012208_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012209{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012210 void *data;
12211 int kind;
12212 Py_ssize_t i, j, len;
12213 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012214 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012215
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012216 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12217 return NULL;
12218
12219 kind = PyUnicode_KIND(self);
12220 data = PyUnicode_DATA(self);
12221 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012222 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12224 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012225 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012226
Benjamin Peterson14339b62009-01-31 16:36:08 +000012227 i = 0;
12228 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012229 while (i < len) {
12230 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12231 if (!BLOOM(sepmask, ch))
12232 break;
12233 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12234 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012235 i++;
12236 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012237 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012238
Benjamin Peterson14339b62009-01-31 16:36:08 +000012239 j = len;
12240 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012241 j--;
12242 while (j >= i) {
12243 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12244 if (!BLOOM(sepmask, ch))
12245 break;
12246 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12247 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012248 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012249 }
12250
Benjamin Peterson29060642009-01-31 22:14:21 +000012251 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012252 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012253
Victor Stinner7931d9a2011-11-04 00:22:48 +010012254 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255}
12256
12257PyObject*
12258PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12259{
12260 unsigned char *data;
12261 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012262 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263
Victor Stinnerde636f32011-10-01 03:55:54 +020012264 if (PyUnicode_READY(self) == -1)
12265 return NULL;
12266
Victor Stinner684d5fd2012-05-03 02:32:34 +020012267 length = PyUnicode_GET_LENGTH(self);
12268 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012269
Victor Stinner684d5fd2012-05-03 02:32:34 +020012270 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012271 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272
Victor Stinnerde636f32011-10-01 03:55:54 +020012273 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012274 PyErr_SetString(PyExc_IndexError, "string index out of range");
12275 return NULL;
12276 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012277 if (start >= length || end < start)
12278 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012279
Victor Stinner684d5fd2012-05-03 02:32:34 +020012280 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012281 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012282 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012283 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012284 }
12285 else {
12286 kind = PyUnicode_KIND(self);
12287 data = PyUnicode_1BYTE_DATA(self);
12288 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012289 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012290 length);
12291 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293
12294static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012295do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 Py_ssize_t len, i, j;
12298
12299 if (PyUnicode_READY(self) == -1)
12300 return NULL;
12301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012303
Victor Stinnercc7af722013-04-09 22:39:24 +020012304 if (PyUnicode_IS_ASCII(self)) {
12305 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12306
12307 i = 0;
12308 if (striptype != RIGHTSTRIP) {
12309 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012310 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012311 if (!_Py_ascii_whitespace[ch])
12312 break;
12313 i++;
12314 }
12315 }
12316
12317 j = len;
12318 if (striptype != LEFTSTRIP) {
12319 j--;
12320 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012321 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012322 if (!_Py_ascii_whitespace[ch])
12323 break;
12324 j--;
12325 }
12326 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012327 }
12328 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012329 else {
12330 int kind = PyUnicode_KIND(self);
12331 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012332
Victor Stinnercc7af722013-04-09 22:39:24 +020012333 i = 0;
12334 if (striptype != RIGHTSTRIP) {
12335 while (i < len) {
12336 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12337 if (!Py_UNICODE_ISSPACE(ch))
12338 break;
12339 i++;
12340 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012341 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012342
12343 j = len;
12344 if (striptype != LEFTSTRIP) {
12345 j--;
12346 while (j >= i) {
12347 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12348 if (!Py_UNICODE_ISSPACE(ch))
12349 break;
12350 j--;
12351 }
12352 j++;
12353 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012354 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012355
Victor Stinner7931d9a2011-11-04 00:22:48 +010012356 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012357}
12358
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012359
12360static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012361do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012362{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012363 if (sep != NULL && sep != Py_None) {
12364 if (PyUnicode_Check(sep))
12365 return _PyUnicode_XStrip(self, striptype, sep);
12366 else {
12367 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012368 "%s arg must be None or str",
12369 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012370 return NULL;
12371 }
12372 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012373
Benjamin Peterson14339b62009-01-31 16:36:08 +000012374 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012375}
12376
12377
INADA Naoki3ae20562017-01-16 20:41:20 +090012378/*[clinic input]
12379str.strip as unicode_strip
12380
12381 chars: object = None
12382 /
12383
Victor Stinner0c4a8282017-01-17 02:21:47 +010012384Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012385
12386If chars is given and not None, remove characters in chars instead.
12387[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012388
12389static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012390unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012391/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012392{
INADA Naoki3ae20562017-01-16 20:41:20 +090012393 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012394}
12395
12396
INADA Naoki3ae20562017-01-16 20:41:20 +090012397/*[clinic input]
12398str.lstrip as unicode_lstrip
12399
12400 chars: object = NULL
12401 /
12402
12403Return a copy of the string with leading whitespace removed.
12404
12405If chars is given and not None, remove characters in chars instead.
12406[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012407
12408static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012409unicode_lstrip_impl(PyObject *self, PyObject *chars)
12410/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012411{
INADA Naoki3ae20562017-01-16 20:41:20 +090012412 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012413}
12414
12415
INADA Naoki3ae20562017-01-16 20:41:20 +090012416/*[clinic input]
12417str.rstrip as unicode_rstrip
12418
12419 chars: object = NULL
12420 /
12421
12422Return a copy of the string with trailing whitespace removed.
12423
12424If chars is given and not None, remove characters in chars instead.
12425[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012426
12427static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012428unicode_rstrip_impl(PyObject *self, PyObject *chars)
12429/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012430{
INADA Naoki3ae20562017-01-16 20:41:20 +090012431 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012432}
12433
12434
Guido van Rossumd57fd912000-03-10 22:53:23 +000012435static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012436unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012438 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012439 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012440
Serhiy Storchaka05997252013-01-26 12:14:02 +020012441 if (len < 1)
12442 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443
Victor Stinnerc4b49542011-12-11 22:44:26 +010012444 /* no repeat, return original string */
12445 if (len == 1)
12446 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012447
Benjamin Petersonbac79492012-01-14 13:34:47 -050012448 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 return NULL;
12450
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012451 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012452 PyErr_SetString(PyExc_OverflowError,
12453 "repeated string is too long");
12454 return NULL;
12455 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012457
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012458 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459 if (!u)
12460 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012461 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012463 if (PyUnicode_GET_LENGTH(str) == 1) {
12464 const int kind = PyUnicode_KIND(str);
12465 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012466 if (kind == PyUnicode_1BYTE_KIND) {
12467 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012468 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012469 }
12470 else if (kind == PyUnicode_2BYTE_KIND) {
12471 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012472 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012473 ucs2[n] = fill_char;
12474 } else {
12475 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12476 assert(kind == PyUnicode_4BYTE_KIND);
12477 for (n = 0; n < len; ++n)
12478 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012479 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 }
12481 else {
12482 /* number of characters copied this far */
12483 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012484 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012485 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012486 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012487 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012488 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012489 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012490 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012491 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012492 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012493 }
12494
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012495 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012496 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012497}
12498
Alexander Belopolsky40018472011-02-26 01:02:56 +000012499PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012500PyUnicode_Replace(PyObject *str,
12501 PyObject *substr,
12502 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012503 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012504{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012505 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12506 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012507 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012508 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509}
12510
INADA Naoki3ae20562017-01-16 20:41:20 +090012511/*[clinic input]
12512str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012513
INADA Naoki3ae20562017-01-16 20:41:20 +090012514 old: unicode
12515 new: unicode
12516 count: Py_ssize_t = -1
12517 Maximum number of occurrences to replace.
12518 -1 (the default value) means replace all occurrences.
12519 /
12520
12521Return a copy with all occurrences of substring old replaced by new.
12522
12523If the optional argument count is given, only the first count occurrences are
12524replaced.
12525[clinic start generated code]*/
12526
12527static PyObject *
12528unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12529 Py_ssize_t count)
12530/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012532 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012533 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012534 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535}
12536
Alexander Belopolsky40018472011-02-26 01:02:56 +000012537static PyObject *
12538unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012540 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 Py_ssize_t isize;
12542 Py_ssize_t osize, squote, dquote, i, o;
12543 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012544 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012545 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012546
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012547 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012548 return NULL;
12549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550 isize = PyUnicode_GET_LENGTH(unicode);
12551 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012552
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553 /* Compute length of output, quote characters, and
12554 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012555 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012556 max = 127;
12557 squote = dquote = 0;
12558 ikind = PyUnicode_KIND(unicode);
12559 for (i = 0; i < isize; i++) {
12560 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012561 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012563 case '\'': squote++; break;
12564 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012566 incr = 2;
12567 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 default:
12569 /* Fast-path ASCII */
12570 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012571 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012573 ;
12574 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012577 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012579 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012580 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012581 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012583 if (osize > PY_SSIZE_T_MAX - incr) {
12584 PyErr_SetString(PyExc_OverflowError,
12585 "string is too long to generate repr");
12586 return NULL;
12587 }
12588 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 }
12590
12591 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012592 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012594 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012595 if (dquote)
12596 /* Both squote and dquote present. Use squote,
12597 and escape them */
12598 osize += squote;
12599 else
12600 quote = '"';
12601 }
Victor Stinner55c08782013-04-14 18:45:39 +020012602 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603
12604 repr = PyUnicode_New(osize, max);
12605 if (repr == NULL)
12606 return NULL;
12607 okind = PyUnicode_KIND(repr);
12608 odata = PyUnicode_DATA(repr);
12609
12610 PyUnicode_WRITE(okind, odata, 0, quote);
12611 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012612 if (unchanged) {
12613 _PyUnicode_FastCopyCharacters(repr, 1,
12614 unicode, 0,
12615 isize);
12616 }
12617 else {
12618 for (i = 0, o = 1; i < isize; i++) {
12619 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620
Victor Stinner55c08782013-04-14 18:45:39 +020012621 /* Escape quotes and backslashes */
12622 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012623 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012624 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012625 continue;
12626 }
12627
12628 /* Map special whitespace to '\t', \n', '\r' */
12629 if (ch == '\t') {
12630 PyUnicode_WRITE(okind, odata, o++, '\\');
12631 PyUnicode_WRITE(okind, odata, o++, 't');
12632 }
12633 else if (ch == '\n') {
12634 PyUnicode_WRITE(okind, odata, o++, '\\');
12635 PyUnicode_WRITE(okind, odata, o++, 'n');
12636 }
12637 else if (ch == '\r') {
12638 PyUnicode_WRITE(okind, odata, o++, '\\');
12639 PyUnicode_WRITE(okind, odata, o++, 'r');
12640 }
12641
12642 /* Map non-printable US ASCII to '\xhh' */
12643 else if (ch < ' ' || ch == 0x7F) {
12644 PyUnicode_WRITE(okind, odata, o++, '\\');
12645 PyUnicode_WRITE(okind, odata, o++, 'x');
12646 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12647 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12648 }
12649
12650 /* Copy ASCII characters as-is */
12651 else if (ch < 0x7F) {
12652 PyUnicode_WRITE(okind, odata, o++, ch);
12653 }
12654
12655 /* Non-ASCII characters */
12656 else {
12657 /* Map Unicode whitespace and control characters
12658 (categories Z* and C* except ASCII space)
12659 */
12660 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12661 PyUnicode_WRITE(okind, odata, o++, '\\');
12662 /* Map 8-bit characters to '\xhh' */
12663 if (ch <= 0xff) {
12664 PyUnicode_WRITE(okind, odata, o++, 'x');
12665 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12666 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12667 }
12668 /* Map 16-bit characters to '\uxxxx' */
12669 else if (ch <= 0xffff) {
12670 PyUnicode_WRITE(okind, odata, o++, 'u');
12671 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12672 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12673 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12674 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12675 }
12676 /* Map 21-bit characters to '\U00xxxxxx' */
12677 else {
12678 PyUnicode_WRITE(okind, odata, o++, 'U');
12679 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12680 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12681 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12682 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12683 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12684 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12685 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12686 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12687 }
12688 }
12689 /* Copy characters as-is */
12690 else {
12691 PyUnicode_WRITE(okind, odata, o++, ch);
12692 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012693 }
12694 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012695 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012696 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012697 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012698 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699}
12700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012701PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012702 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703\n\
12704Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012705such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706arguments start and end are interpreted as in slice notation.\n\
12707\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012708Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709
12710static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012713 /* initialize variables to prevent gcc warning */
12714 PyObject *substring = NULL;
12715 Py_ssize_t start = 0;
12716 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012717 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012719 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012720 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012722 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012725 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 if (result == -2)
12728 return NULL;
12729
Christian Heimes217cfd12007-12-02 14:31:20 +000012730 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731}
12732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012733PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012734 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012736Return the highest index in S where substring sub is found,\n\
12737such that sub is contained within S[start:end]. Optional\n\
12738arguments start and end are interpreted as in slice notation.\n\
12739\n\
12740Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741
12742static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012745 /* initialize variables to prevent gcc warning */
12746 PyObject *substring = NULL;
12747 Py_ssize_t start = 0;
12748 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012749 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012751 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012752 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012753
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012754 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012755 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012757 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012758
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012759 if (result == -2)
12760 return NULL;
12761
Guido van Rossumd57fd912000-03-10 22:53:23 +000012762 if (result < 0) {
12763 PyErr_SetString(PyExc_ValueError, "substring not found");
12764 return NULL;
12765 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012766
Christian Heimes217cfd12007-12-02 14:31:20 +000012767 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768}
12769
INADA Naoki3ae20562017-01-16 20:41:20 +090012770/*[clinic input]
12771str.rjust as unicode_rjust
12772
12773 width: Py_ssize_t
12774 fillchar: Py_UCS4 = ' '
12775 /
12776
12777Return a right-justified string of length width.
12778
12779Padding is done using the specified fill character (default is a space).
12780[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781
12782static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012783unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12784/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012786 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787 return NULL;
12788
Victor Stinnerc4b49542011-12-11 22:44:26 +010012789 if (PyUnicode_GET_LENGTH(self) >= width)
12790 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791
Victor Stinnerc4b49542011-12-11 22:44:26 +010012792 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793}
12794
Alexander Belopolsky40018472011-02-26 01:02:56 +000012795PyObject *
12796PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012798 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012799 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012801 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802}
12803
INADA Naoki3ae20562017-01-16 20:41:20 +090012804/*[clinic input]
12805str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806
INADA Naoki3ae20562017-01-16 20:41:20 +090012807 sep: object = None
12808 The delimiter according which to split the string.
12809 None (the default value) means split according to any whitespace,
12810 and discard empty strings from the result.
12811 maxsplit: Py_ssize_t = -1
12812 Maximum number of splits to do.
12813 -1 (the default value) means no limit.
12814
12815Return a list of the words in the string, using sep as the delimiter string.
12816[clinic start generated code]*/
12817
12818static PyObject *
12819unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12820/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012821{
INADA Naoki3ae20562017-01-16 20:41:20 +090012822 if (sep == Py_None)
12823 return split(self, NULL, maxsplit);
12824 if (PyUnicode_Check(sep))
12825 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012826
12827 PyErr_Format(PyExc_TypeError,
12828 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012829 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012830 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831}
12832
Thomas Wouters477c8d52006-05-27 19:21:47 +000012833PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012834PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012835{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012836 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012837 int kind1, kind2;
12838 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012839 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012840
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012841 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012842 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012843
Victor Stinner14f8f022011-10-05 20:58:25 +020012844 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012845 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012846 len1 = PyUnicode_GET_LENGTH(str_obj);
12847 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012848 if (kind1 < kind2 || len1 < len2) {
12849 _Py_INCREF_UNICODE_EMPTY();
12850 if (!unicode_empty)
12851 out = NULL;
12852 else {
12853 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12854 Py_DECREF(unicode_empty);
12855 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012856 return out;
12857 }
12858 buf1 = PyUnicode_DATA(str_obj);
12859 buf2 = PyUnicode_DATA(sep_obj);
12860 if (kind2 != kind1) {
12861 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12862 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012863 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012864 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012865
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012866 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012867 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012868 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12869 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12870 else
12871 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012872 break;
12873 case PyUnicode_2BYTE_KIND:
12874 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12875 break;
12876 case PyUnicode_4BYTE_KIND:
12877 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12878 break;
12879 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012880 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012882
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012883 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012884 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012885
12886 return out;
12887}
12888
12889
12890PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012891PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012892{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012893 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012894 int kind1, kind2;
12895 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012896 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012897
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012898 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012899 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012900
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012901 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012903 len1 = PyUnicode_GET_LENGTH(str_obj);
12904 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012905 if (kind1 < kind2 || len1 < len2) {
12906 _Py_INCREF_UNICODE_EMPTY();
12907 if (!unicode_empty)
12908 out = NULL;
12909 else {
12910 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12911 Py_DECREF(unicode_empty);
12912 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012913 return out;
12914 }
12915 buf1 = PyUnicode_DATA(str_obj);
12916 buf2 = PyUnicode_DATA(sep_obj);
12917 if (kind2 != kind1) {
12918 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12919 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012920 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012922
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012923 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012925 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12926 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12927 else
12928 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012929 break;
12930 case PyUnicode_2BYTE_KIND:
12931 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12932 break;
12933 case PyUnicode_4BYTE_KIND:
12934 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12935 break;
12936 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012937 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012938 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012939
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012940 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012941 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012942
12943 return out;
12944}
12945
INADA Naoki3ae20562017-01-16 20:41:20 +090012946/*[clinic input]
12947str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012948
INADA Naoki3ae20562017-01-16 20:41:20 +090012949 sep: object
12950 /
12951
12952Partition the string into three parts using the given separator.
12953
12954This will search for the separator in the string. If the separator is found,
12955returns a 3-tuple containing the part before the separator, the separator
12956itself, and the part after it.
12957
12958If the separator is not found, returns a 3-tuple containing the original string
12959and two empty strings.
12960[clinic start generated code]*/
12961
12962static PyObject *
12963unicode_partition(PyObject *self, PyObject *sep)
12964/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012965{
INADA Naoki3ae20562017-01-16 20:41:20 +090012966 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012967}
12968
INADA Naoki3ae20562017-01-16 20:41:20 +090012969/*[clinic input]
12970str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012971
INADA Naoki3ae20562017-01-16 20:41:20 +090012972Partition the string into three parts using the given separator.
12973
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012974This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012975the separator is found, returns a 3-tuple containing the part before the
12976separator, the separator itself, and the part after it.
12977
12978If the separator is not found, returns a 3-tuple containing two empty strings
12979and the original string.
12980[clinic start generated code]*/
12981
12982static PyObject *
12983unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012984/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012985{
INADA Naoki3ae20562017-01-16 20:41:20 +090012986 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012987}
12988
Alexander Belopolsky40018472011-02-26 01:02:56 +000012989PyObject *
12990PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012991{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012992 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012993 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012994
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012995 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012996}
12997
INADA Naoki3ae20562017-01-16 20:41:20 +090012998/*[clinic input]
12999str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013000
INADA Naoki3ae20562017-01-16 20:41:20 +090013001Return a list of the words in the string, using sep as the delimiter string.
13002
13003Splits are done starting at the end of the string and working to the front.
13004[clinic start generated code]*/
13005
13006static PyObject *
13007unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13008/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013009{
INADA Naoki3ae20562017-01-16 20:41:20 +090013010 if (sep == Py_None)
13011 return rsplit(self, NULL, maxsplit);
13012 if (PyUnicode_Check(sep))
13013 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013014
13015 PyErr_Format(PyExc_TypeError,
13016 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013017 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013018 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013019}
13020
INADA Naoki3ae20562017-01-16 20:41:20 +090013021/*[clinic input]
13022str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013023
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013024 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013025
13026Return a list of the lines in the string, breaking at line boundaries.
13027
13028Line breaks are not included in the resulting list unless keepends is given and
13029true.
13030[clinic start generated code]*/
13031
13032static PyObject *
13033unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013034/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013035{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013036 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013037}
13038
13039static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013040PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013041{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013042 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013043}
13044
INADA Naoki3ae20562017-01-16 20:41:20 +090013045/*[clinic input]
13046str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013047
INADA Naoki3ae20562017-01-16 20:41:20 +090013048Convert uppercase characters to lowercase and lowercase characters to uppercase.
13049[clinic start generated code]*/
13050
13051static PyObject *
13052unicode_swapcase_impl(PyObject *self)
13053/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013055 if (PyUnicode_READY(self) == -1)
13056 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013057 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013058}
13059
Larry Hastings61272b72014-01-07 12:41:53 -080013060/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013061
Larry Hastings31826802013-10-19 00:09:25 -070013062@staticmethod
13063str.maketrans as unicode_maketrans
13064
13065 x: object
13066
13067 y: unicode=NULL
13068
13069 z: unicode=NULL
13070
13071 /
13072
13073Return a translation table usable for str.translate().
13074
13075If there is only one argument, it must be a dictionary mapping Unicode
13076ordinals (integers) or characters to Unicode ordinals, strings or None.
13077Character keys will be then converted to ordinals.
13078If there are two arguments, they must be strings of equal length, and
13079in the resulting dictionary, each character in x will be mapped to the
13080character at the same position in y. If there is a third argument, it
13081must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013082[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013083
Larry Hastings31826802013-10-19 00:09:25 -070013084static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013085unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013086/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013087{
Georg Brandlceee0772007-11-27 23:48:05 +000013088 PyObject *new = NULL, *key, *value;
13089 Py_ssize_t i = 0;
13090 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013091
Georg Brandlceee0772007-11-27 23:48:05 +000013092 new = PyDict_New();
13093 if (!new)
13094 return NULL;
13095 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013096 int x_kind, y_kind, z_kind;
13097 void *x_data, *y_data, *z_data;
13098
Georg Brandlceee0772007-11-27 23:48:05 +000013099 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013100 if (!PyUnicode_Check(x)) {
13101 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13102 "be a string if there is a second argument");
13103 goto err;
13104 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013105 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013106 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13107 "arguments must have equal length");
13108 goto err;
13109 }
13110 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013111 x_kind = PyUnicode_KIND(x);
13112 y_kind = PyUnicode_KIND(y);
13113 x_data = PyUnicode_DATA(x);
13114 y_data = PyUnicode_DATA(y);
13115 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13116 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013117 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013118 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013119 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013120 if (!value) {
13121 Py_DECREF(key);
13122 goto err;
13123 }
Georg Brandlceee0772007-11-27 23:48:05 +000013124 res = PyDict_SetItem(new, key, value);
13125 Py_DECREF(key);
13126 Py_DECREF(value);
13127 if (res < 0)
13128 goto err;
13129 }
13130 /* create entries for deleting chars in z */
13131 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013132 z_kind = PyUnicode_KIND(z);
13133 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013134 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013135 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013136 if (!key)
13137 goto err;
13138 res = PyDict_SetItem(new, key, Py_None);
13139 Py_DECREF(key);
13140 if (res < 0)
13141 goto err;
13142 }
13143 }
13144 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 int kind;
13146 void *data;
13147
Georg Brandlceee0772007-11-27 23:48:05 +000013148 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013149 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013150 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13151 "to maketrans it must be a dict");
13152 goto err;
13153 }
13154 /* copy entries into the new dict, converting string keys to int keys */
13155 while (PyDict_Next(x, &i, &key, &value)) {
13156 if (PyUnicode_Check(key)) {
13157 /* convert string keys to integer keys */
13158 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013159 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013160 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13161 "table must be of length 1");
13162 goto err;
13163 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013164 kind = PyUnicode_KIND(key);
13165 data = PyUnicode_DATA(key);
13166 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013167 if (!newkey)
13168 goto err;
13169 res = PyDict_SetItem(new, newkey, value);
13170 Py_DECREF(newkey);
13171 if (res < 0)
13172 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013173 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013174 /* just keep integer keys */
13175 if (PyDict_SetItem(new, key, value) < 0)
13176 goto err;
13177 } else {
13178 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13179 "be strings or integers");
13180 goto err;
13181 }
13182 }
13183 }
13184 return new;
13185 err:
13186 Py_DECREF(new);
13187 return NULL;
13188}
13189
INADA Naoki3ae20562017-01-16 20:41:20 +090013190/*[clinic input]
13191str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192
INADA Naoki3ae20562017-01-16 20:41:20 +090013193 table: object
13194 Translation table, which must be a mapping of Unicode ordinals to
13195 Unicode ordinals, strings, or None.
13196 /
13197
13198Replace each character in the string using the given translation table.
13199
13200The table must implement lookup/indexing via __getitem__, for instance a
13201dictionary or list. If this operation raises LookupError, the character is
13202left untouched. Characters mapped to None are deleted.
13203[clinic start generated code]*/
13204
13205static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013206unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013207/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013209 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210}
13211
INADA Naoki3ae20562017-01-16 20:41:20 +090013212/*[clinic input]
13213str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214
INADA Naoki3ae20562017-01-16 20:41:20 +090013215Return a copy of the string converted to uppercase.
13216[clinic start generated code]*/
13217
13218static PyObject *
13219unicode_upper_impl(PyObject *self)
13220/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013222 if (PyUnicode_READY(self) == -1)
13223 return NULL;
13224 if (PyUnicode_IS_ASCII(self))
13225 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013226 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227}
13228
INADA Naoki3ae20562017-01-16 20:41:20 +090013229/*[clinic input]
13230str.zfill as unicode_zfill
13231
13232 width: Py_ssize_t
13233 /
13234
13235Pad a numeric string with zeros on the left, to fill a field of the given width.
13236
13237The string is never truncated.
13238[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013239
13240static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013241unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013242/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013243{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013244 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013245 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013246 int kind;
13247 void *data;
13248 Py_UCS4 chr;
13249
Benjamin Petersonbac79492012-01-14 13:34:47 -050013250 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013251 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013252
Victor Stinnerc4b49542011-12-11 22:44:26 +010013253 if (PyUnicode_GET_LENGTH(self) >= width)
13254 return unicode_result_unchanged(self);
13255
13256 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013257
13258 u = pad(self, fill, 0, '0');
13259
Walter Dörwald068325e2002-04-15 13:36:47 +000013260 if (u == NULL)
13261 return NULL;
13262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013263 kind = PyUnicode_KIND(u);
13264 data = PyUnicode_DATA(u);
13265 chr = PyUnicode_READ(kind, data, fill);
13266
13267 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013268 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013269 PyUnicode_WRITE(kind, data, 0, chr);
13270 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013271 }
13272
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013273 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013274 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013276
13277#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013278static PyObject *
13279unicode__decimal2ascii(PyObject *self)
13280{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013281 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013282}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013283#endif
13284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013285PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013286 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013287\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013288Return True if S starts with the specified prefix, False otherwise.\n\
13289With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013290With optional end, stop comparing S at that position.\n\
13291prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013292
13293static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013294unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013295 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013296{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013297 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013298 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013299 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013300 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013301 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302
Jesus Ceaac451502011-04-20 17:09:23 +020013303 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013304 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013305 if (PyTuple_Check(subobj)) {
13306 Py_ssize_t i;
13307 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013308 substring = PyTuple_GET_ITEM(subobj, i);
13309 if (!PyUnicode_Check(substring)) {
13310 PyErr_Format(PyExc_TypeError,
13311 "tuple for startswith must only contain str, "
13312 "not %.100s",
13313 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013314 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013315 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013316 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013317 if (result == -1)
13318 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013319 if (result) {
13320 Py_RETURN_TRUE;
13321 }
13322 }
13323 /* nothing matched */
13324 Py_RETURN_FALSE;
13325 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013326 if (!PyUnicode_Check(subobj)) {
13327 PyErr_Format(PyExc_TypeError,
13328 "startswith first arg must be str or "
13329 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013330 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013331 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013332 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013333 if (result == -1)
13334 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013335 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013336}
13337
13338
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013339PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013340 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013341\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013342Return True if S ends with the specified suffix, False otherwise.\n\
13343With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013344With optional end, stop comparing S at that position.\n\
13345suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013346
13347static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013348unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013349 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013350{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013351 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013352 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013353 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013354 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013355 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013356
Jesus Ceaac451502011-04-20 17:09:23 +020013357 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013358 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013359 if (PyTuple_Check(subobj)) {
13360 Py_ssize_t i;
13361 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013362 substring = PyTuple_GET_ITEM(subobj, i);
13363 if (!PyUnicode_Check(substring)) {
13364 PyErr_Format(PyExc_TypeError,
13365 "tuple for endswith must only contain str, "
13366 "not %.100s",
13367 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013368 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013369 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013370 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013371 if (result == -1)
13372 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013373 if (result) {
13374 Py_RETURN_TRUE;
13375 }
13376 }
13377 Py_RETURN_FALSE;
13378 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013379 if (!PyUnicode_Check(subobj)) {
13380 PyErr_Format(PyExc_TypeError,
13381 "endswith first arg must be str or "
13382 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013383 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013384 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013385 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013386 if (result == -1)
13387 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013388 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013389}
13390
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013391static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013392_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013393{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013394 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13395 writer->data = PyUnicode_DATA(writer->buffer);
13396
13397 if (!writer->readonly) {
13398 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013399 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013400 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013401 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013402 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13403 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13404 writer->kind = PyUnicode_WCHAR_KIND;
13405 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13406
Victor Stinner8f674cc2013-04-17 23:02:17 +020013407 /* Copy-on-write mode: set buffer size to 0 so
13408 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13409 * next write. */
13410 writer->size = 0;
13411 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013412}
13413
Victor Stinnerd3f08822012-05-29 12:57:52 +020013414void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013415_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013416{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013417 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013418
13419 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013420 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013421
13422 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13423 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13424 writer->kind = PyUnicode_WCHAR_KIND;
13425 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013426}
13427
Victor Stinnerd3f08822012-05-29 12:57:52 +020013428int
13429_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13430 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013431{
13432 Py_ssize_t newlen;
13433 PyObject *newbuffer;
13434
Victor Stinner2740e462016-09-06 16:58:36 -070013435 assert(maxchar <= MAX_UNICODE);
13436
Victor Stinnerca9381e2015-09-22 00:58:32 +020013437 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013438 assert((maxchar > writer->maxchar && length >= 0)
13439 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013440
Victor Stinner202fdca2012-05-07 12:47:02 +020013441 if (length > PY_SSIZE_T_MAX - writer->pos) {
13442 PyErr_NoMemory();
13443 return -1;
13444 }
13445 newlen = writer->pos + length;
13446
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013447 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013448
Victor Stinnerd3f08822012-05-29 12:57:52 +020013449 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013450 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013451 if (writer->overallocate
13452 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13453 /* overallocate to limit the number of realloc() */
13454 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013455 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013456 if (newlen < writer->min_length)
13457 newlen = writer->min_length;
13458
Victor Stinnerd3f08822012-05-29 12:57:52 +020013459 writer->buffer = PyUnicode_New(newlen, maxchar);
13460 if (writer->buffer == NULL)
13461 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013462 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013463 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013464 if (writer->overallocate
13465 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13466 /* overallocate to limit the number of realloc() */
13467 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013468 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013469 if (newlen < writer->min_length)
13470 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013471
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013472 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013473 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013474 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013475 newbuffer = PyUnicode_New(newlen, maxchar);
13476 if (newbuffer == NULL)
13477 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013478 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13479 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013480 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013481 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013482 }
13483 else {
13484 newbuffer = resize_compact(writer->buffer, newlen);
13485 if (newbuffer == NULL)
13486 return -1;
13487 }
13488 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013489 }
13490 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013491 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013492 newbuffer = PyUnicode_New(writer->size, maxchar);
13493 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013494 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013495 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13496 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013497 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013498 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013499 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013500 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013501
13502#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013503}
13504
Victor Stinnerca9381e2015-09-22 00:58:32 +020013505int
13506_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13507 enum PyUnicode_Kind kind)
13508{
13509 Py_UCS4 maxchar;
13510
13511 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13512 assert(writer->kind < kind);
13513
13514 switch (kind)
13515 {
13516 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13517 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13518 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13519 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013520 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013521 }
13522
13523 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13524}
13525
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013526static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013527_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013528{
Victor Stinner2740e462016-09-06 16:58:36 -070013529 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013530 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13531 return -1;
13532 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13533 writer->pos++;
13534 return 0;
13535}
13536
13537int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013538_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13539{
13540 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13541}
13542
13543int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13545{
13546 Py_UCS4 maxchar;
13547 Py_ssize_t len;
13548
13549 if (PyUnicode_READY(str) == -1)
13550 return -1;
13551 len = PyUnicode_GET_LENGTH(str);
13552 if (len == 0)
13553 return 0;
13554 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13555 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013556 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013557 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013558 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013559 Py_INCREF(str);
13560 writer->buffer = str;
13561 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013562 writer->pos += len;
13563 return 0;
13564 }
13565 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13566 return -1;
13567 }
13568 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13569 str, 0, len);
13570 writer->pos += len;
13571 return 0;
13572}
13573
Victor Stinnere215d962012-10-06 23:03:36 +020013574int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013575_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13576 Py_ssize_t start, Py_ssize_t end)
13577{
13578 Py_UCS4 maxchar;
13579 Py_ssize_t len;
13580
13581 if (PyUnicode_READY(str) == -1)
13582 return -1;
13583
13584 assert(0 <= start);
13585 assert(end <= PyUnicode_GET_LENGTH(str));
13586 assert(start <= end);
13587
13588 if (end == 0)
13589 return 0;
13590
13591 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13592 return _PyUnicodeWriter_WriteStr(writer, str);
13593
13594 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13595 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13596 else
13597 maxchar = writer->maxchar;
13598 len = end - start;
13599
13600 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13601 return -1;
13602
13603 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13604 str, start, len);
13605 writer->pos += len;
13606 return 0;
13607}
13608
13609int
Victor Stinner4a587072013-11-19 12:54:53 +010013610_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13611 const char *ascii, Py_ssize_t len)
13612{
13613 if (len == -1)
13614 len = strlen(ascii);
13615
13616 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13617
13618 if (writer->buffer == NULL && !writer->overallocate) {
13619 PyObject *str;
13620
13621 str = _PyUnicode_FromASCII(ascii, len);
13622 if (str == NULL)
13623 return -1;
13624
13625 writer->readonly = 1;
13626 writer->buffer = str;
13627 _PyUnicodeWriter_Update(writer);
13628 writer->pos += len;
13629 return 0;
13630 }
13631
13632 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13633 return -1;
13634
13635 switch (writer->kind)
13636 {
13637 case PyUnicode_1BYTE_KIND:
13638 {
13639 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13640 Py_UCS1 *data = writer->data;
13641
Christian Heimesf051e432016-09-13 20:22:02 +020013642 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013643 break;
13644 }
13645 case PyUnicode_2BYTE_KIND:
13646 {
13647 _PyUnicode_CONVERT_BYTES(
13648 Py_UCS1, Py_UCS2,
13649 ascii, ascii + len,
13650 (Py_UCS2 *)writer->data + writer->pos);
13651 break;
13652 }
13653 case PyUnicode_4BYTE_KIND:
13654 {
13655 _PyUnicode_CONVERT_BYTES(
13656 Py_UCS1, Py_UCS4,
13657 ascii, ascii + len,
13658 (Py_UCS4 *)writer->data + writer->pos);
13659 break;
13660 }
13661 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013662 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013663 }
13664
13665 writer->pos += len;
13666 return 0;
13667}
13668
13669int
13670_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13671 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013672{
13673 Py_UCS4 maxchar;
13674
13675 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13676 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13677 return -1;
13678 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13679 writer->pos += len;
13680 return 0;
13681}
13682
Victor Stinnerd3f08822012-05-29 12:57:52 +020013683PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013684_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013685{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013686 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013687
Victor Stinnerd3f08822012-05-29 12:57:52 +020013688 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013689 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013690 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013691 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013692
13693 str = writer->buffer;
13694 writer->buffer = NULL;
13695
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013696 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013697 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13698 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013699 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013700
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013701 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13702 PyObject *str2;
13703 str2 = resize_compact(str, writer->pos);
13704 if (str2 == NULL) {
13705 Py_DECREF(str);
13706 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013707 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013708 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013709 }
13710
Victor Stinner15a0bd32013-07-08 22:29:55 +020013711 assert(_PyUnicode_CheckConsistency(str, 1));
13712 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013713}
13714
Victor Stinnerd3f08822012-05-29 12:57:52 +020013715void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013716_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013717{
13718 Py_CLEAR(writer->buffer);
13719}
13720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013721#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013722
13723PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013724 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013725\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013726Return a formatted version of S, using substitutions from args and kwargs.\n\
13727The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013728
Eric Smith27bbca62010-11-04 17:06:58 +000013729PyDoc_STRVAR(format_map__doc__,
13730 "S.format_map(mapping) -> str\n\
13731\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013732Return a formatted version of S, using substitutions from mapping.\n\
13733The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013734
INADA Naoki3ae20562017-01-16 20:41:20 +090013735/*[clinic input]
13736str.__format__ as unicode___format__
13737
13738 format_spec: unicode
13739 /
13740
13741Return a formatted version of the string as described by format_spec.
13742[clinic start generated code]*/
13743
Eric Smith4a7d76d2008-05-30 18:10:19 +000013744static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013745unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013746/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013747{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013748 _PyUnicodeWriter writer;
13749 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013750
Victor Stinnerd3f08822012-05-29 12:57:52 +020013751 if (PyUnicode_READY(self) == -1)
13752 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013753 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013754 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13755 self, format_spec, 0,
13756 PyUnicode_GET_LENGTH(format_spec));
13757 if (ret == -1) {
13758 _PyUnicodeWriter_Dealloc(&writer);
13759 return NULL;
13760 }
13761 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013762}
13763
INADA Naoki3ae20562017-01-16 20:41:20 +090013764/*[clinic input]
13765str.__sizeof__ as unicode_sizeof
13766
13767Return the size of the string in memory, in bytes.
13768[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013769
13770static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013771unicode_sizeof_impl(PyObject *self)
13772/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013774 Py_ssize_t size;
13775
13776 /* If it's a compact object, account for base structure +
13777 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013778 if (PyUnicode_IS_COMPACT_ASCII(self))
13779 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13780 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013781 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013782 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013783 else {
13784 /* If it is a two-block object, account for base object, and
13785 for character block if present. */
13786 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013787 if (_PyUnicode_DATA_ANY(self))
13788 size += (PyUnicode_GET_LENGTH(self) + 1) *
13789 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013790 }
13791 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013792 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013793 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13794 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13795 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13796 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013797
13798 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013799}
13800
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013801static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013802unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013803{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013804 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013805 if (!copy)
13806 return NULL;
13807 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013808}
13809
Guido van Rossumd57fd912000-03-10 22:53:23 +000013810static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013811 UNICODE_ENCODE_METHODDEF
13812 UNICODE_REPLACE_METHODDEF
13813 UNICODE_SPLIT_METHODDEF
13814 UNICODE_RSPLIT_METHODDEF
13815 UNICODE_JOIN_METHODDEF
13816 UNICODE_CAPITALIZE_METHODDEF
13817 UNICODE_CASEFOLD_METHODDEF
13818 UNICODE_TITLE_METHODDEF
13819 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013820 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013821 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013822 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013823 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013824 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013825 UNICODE_LJUST_METHODDEF
13826 UNICODE_LOWER_METHODDEF
13827 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013828 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13829 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013830 UNICODE_RJUST_METHODDEF
13831 UNICODE_RSTRIP_METHODDEF
13832 UNICODE_RPARTITION_METHODDEF
13833 UNICODE_SPLITLINES_METHODDEF
13834 UNICODE_STRIP_METHODDEF
13835 UNICODE_SWAPCASE_METHODDEF
13836 UNICODE_TRANSLATE_METHODDEF
13837 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013838 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13839 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013840 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013841 UNICODE_ISLOWER_METHODDEF
13842 UNICODE_ISUPPER_METHODDEF
13843 UNICODE_ISTITLE_METHODDEF
13844 UNICODE_ISSPACE_METHODDEF
13845 UNICODE_ISDECIMAL_METHODDEF
13846 UNICODE_ISDIGIT_METHODDEF
13847 UNICODE_ISNUMERIC_METHODDEF
13848 UNICODE_ISALPHA_METHODDEF
13849 UNICODE_ISALNUM_METHODDEF
13850 UNICODE_ISIDENTIFIER_METHODDEF
13851 UNICODE_ISPRINTABLE_METHODDEF
13852 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013853 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013854 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013855 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013856 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013857 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013858#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013859 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013860 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013861#endif
13862
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013863 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013864 {NULL, NULL}
13865};
13866
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013867static PyObject *
13868unicode_mod(PyObject *v, PyObject *w)
13869{
Brian Curtindfc80e32011-08-10 20:28:54 -050013870 if (!PyUnicode_Check(v))
13871 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013872 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013873}
13874
13875static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013876 0, /*nb_add*/
13877 0, /*nb_subtract*/
13878 0, /*nb_multiply*/
13879 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013880};
13881
Guido van Rossumd57fd912000-03-10 22:53:23 +000013882static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013883 (lenfunc) unicode_length, /* sq_length */
13884 PyUnicode_Concat, /* sq_concat */
13885 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13886 (ssizeargfunc) unicode_getitem, /* sq_item */
13887 0, /* sq_slice */
13888 0, /* sq_ass_item */
13889 0, /* sq_ass_slice */
13890 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013891};
13892
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013893static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013894unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013896 if (PyUnicode_READY(self) == -1)
13897 return NULL;
13898
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013899 if (PyIndex_Check(item)) {
13900 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013901 if (i == -1 && PyErr_Occurred())
13902 return NULL;
13903 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013904 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013905 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013906 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013907 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013908 PyObject *result;
13909 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013910 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013911 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013912
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013913 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013914 return NULL;
13915 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013916 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13917 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013918
13919 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013920 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013921 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013922 slicelength == PyUnicode_GET_LENGTH(self)) {
13923 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013924 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013925 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013926 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013927 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013928 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013929 src_kind = PyUnicode_KIND(self);
13930 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013931 if (!PyUnicode_IS_ASCII(self)) {
13932 kind_limit = kind_maxchar_limit(src_kind);
13933 max_char = 0;
13934 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13935 ch = PyUnicode_READ(src_kind, src_data, cur);
13936 if (ch > max_char) {
13937 max_char = ch;
13938 if (max_char >= kind_limit)
13939 break;
13940 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013941 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013942 }
Victor Stinner55c99112011-10-13 01:17:06 +020013943 else
13944 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013945 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013946 if (result == NULL)
13947 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013948 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013949 dest_data = PyUnicode_DATA(result);
13950
13951 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013952 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13953 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013954 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013955 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013956 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013957 } else {
13958 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13959 return NULL;
13960 }
13961}
13962
13963static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 (lenfunc)unicode_length, /* mp_length */
13965 (binaryfunc)unicode_subscript, /* mp_subscript */
13966 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013967};
13968
Guido van Rossumd57fd912000-03-10 22:53:23 +000013969
Guido van Rossumd57fd912000-03-10 22:53:23 +000013970/* Helpers for PyUnicode_Format() */
13971
Victor Stinnera47082312012-10-04 02:19:54 +020013972struct unicode_formatter_t {
13973 PyObject *args;
13974 int args_owned;
13975 Py_ssize_t arglen, argidx;
13976 PyObject *dict;
13977
13978 enum PyUnicode_Kind fmtkind;
13979 Py_ssize_t fmtcnt, fmtpos;
13980 void *fmtdata;
13981 PyObject *fmtstr;
13982
13983 _PyUnicodeWriter writer;
13984};
13985
13986struct unicode_format_arg_t {
13987 Py_UCS4 ch;
13988 int flags;
13989 Py_ssize_t width;
13990 int prec;
13991 int sign;
13992};
13993
Guido van Rossumd57fd912000-03-10 22:53:23 +000013994static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013995unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013996{
Victor Stinnera47082312012-10-04 02:19:54 +020013997 Py_ssize_t argidx = ctx->argidx;
13998
13999 if (argidx < ctx->arglen) {
14000 ctx->argidx++;
14001 if (ctx->arglen < 0)
14002 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014003 else
Victor Stinnera47082312012-10-04 02:19:54 +020014004 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014005 }
14006 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014007 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014008 return NULL;
14009}
14010
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014011/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014012
Victor Stinnera47082312012-10-04 02:19:54 +020014013/* Format a float into the writer if the writer is not NULL, or into *p_output
14014 otherwise.
14015
14016 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014017static int
Victor Stinnera47082312012-10-04 02:19:54 +020014018formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14019 PyObject **p_output,
14020 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014021{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014022 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014023 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014024 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014025 int prec;
14026 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014027
Guido van Rossumd57fd912000-03-10 22:53:23 +000014028 x = PyFloat_AsDouble(v);
14029 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014030 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014031
Victor Stinnera47082312012-10-04 02:19:54 +020014032 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014033 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014034 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014035
Victor Stinnera47082312012-10-04 02:19:54 +020014036 if (arg->flags & F_ALT)
14037 dtoa_flags = Py_DTSF_ALT;
14038 else
14039 dtoa_flags = 0;
14040 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014041 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014042 return -1;
14043 len = strlen(p);
14044 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014045 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014046 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014047 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014048 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014049 }
14050 else
14051 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014052 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014053 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014054}
14055
Victor Stinnerd0880d52012-04-27 23:40:13 +020014056/* formatlong() emulates the format codes d, u, o, x and X, and
14057 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14058 * Python's regular ints.
14059 * Return value: a new PyUnicodeObject*, or NULL if error.
14060 * The output string is of the form
14061 * "-"? ("0x" | "0X")? digit+
14062 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14063 * set in flags. The case of hex digits will be correct,
14064 * There will be at least prec digits, zero-filled on the left if
14065 * necessary to get that many.
14066 * val object to be converted
14067 * flags bitmask of format flags; only F_ALT is looked at
14068 * prec minimum number of digits; 0-fill on left if needed
14069 * type a character in [duoxX]; u acts the same as d
14070 *
14071 * CAUTION: o, x and X conversions on regular ints can never
14072 * produce a '-' sign, but can for Python's unbounded ints.
14073 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014074PyObject *
14075_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014076{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014077 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014078 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014079 Py_ssize_t i;
14080 int sign; /* 1 if '-', else 0 */
14081 int len; /* number of characters */
14082 Py_ssize_t llen;
14083 int numdigits; /* len == numnondigits + numdigits */
14084 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014085
Victor Stinnerd0880d52012-04-27 23:40:13 +020014086 /* Avoid exceeding SSIZE_T_MAX */
14087 if (prec > INT_MAX-3) {
14088 PyErr_SetString(PyExc_OverflowError,
14089 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014090 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014091 }
14092
14093 assert(PyLong_Check(val));
14094
14095 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014096 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014097 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014098 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014099 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014100 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014101 /* int and int subclasses should print numerically when a numeric */
14102 /* format code is used (see issue18780) */
14103 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014104 break;
14105 case 'o':
14106 numnondigits = 2;
14107 result = PyNumber_ToBase(val, 8);
14108 break;
14109 case 'x':
14110 case 'X':
14111 numnondigits = 2;
14112 result = PyNumber_ToBase(val, 16);
14113 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014114 }
14115 if (!result)
14116 return NULL;
14117
14118 assert(unicode_modifiable(result));
14119 assert(PyUnicode_IS_READY(result));
14120 assert(PyUnicode_IS_ASCII(result));
14121
14122 /* To modify the string in-place, there can only be one reference. */
14123 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014124 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014125 PyErr_BadInternalCall();
14126 return NULL;
14127 }
14128 buf = PyUnicode_DATA(result);
14129 llen = PyUnicode_GET_LENGTH(result);
14130 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014131 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014132 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014133 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014134 return NULL;
14135 }
14136 len = (int)llen;
14137 sign = buf[0] == '-';
14138 numnondigits += sign;
14139 numdigits = len - numnondigits;
14140 assert(numdigits > 0);
14141
14142 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014143 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014144 (type == 'o' || type == 'x' || type == 'X'))) {
14145 assert(buf[sign] == '0');
14146 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14147 buf[sign+1] == 'o');
14148 numnondigits -= 2;
14149 buf += 2;
14150 len -= 2;
14151 if (sign)
14152 buf[0] = '-';
14153 assert(len == numnondigits + numdigits);
14154 assert(numdigits > 0);
14155 }
14156
14157 /* Fill with leading zeroes to meet minimum width. */
14158 if (prec > numdigits) {
14159 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14160 numnondigits + prec);
14161 char *b1;
14162 if (!r1) {
14163 Py_DECREF(result);
14164 return NULL;
14165 }
14166 b1 = PyBytes_AS_STRING(r1);
14167 for (i = 0; i < numnondigits; ++i)
14168 *b1++ = *buf++;
14169 for (i = 0; i < prec - numdigits; i++)
14170 *b1++ = '0';
14171 for (i = 0; i < numdigits; i++)
14172 *b1++ = *buf++;
14173 *b1 = '\0';
14174 Py_DECREF(result);
14175 result = r1;
14176 buf = PyBytes_AS_STRING(result);
14177 len = numnondigits + prec;
14178 }
14179
14180 /* Fix up case for hex conversions. */
14181 if (type == 'X') {
14182 /* Need to convert all lower case letters to upper case.
14183 and need to convert 0x to 0X (and -0x to -0X). */
14184 for (i = 0; i < len; i++)
14185 if (buf[i] >= 'a' && buf[i] <= 'x')
14186 buf[i] -= 'a'-'A';
14187 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014188 if (!PyUnicode_Check(result)
14189 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014190 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014191 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014192 Py_DECREF(result);
14193 result = unicode;
14194 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014195 else if (len != PyUnicode_GET_LENGTH(result)) {
14196 if (PyUnicode_Resize(&result, len) < 0)
14197 Py_CLEAR(result);
14198 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014199 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014200}
14201
Ethan Furmandf3ed242014-01-05 06:50:30 -080014202/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014203 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014204 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014205 * -1 and raise an exception on error */
14206static int
Victor Stinnera47082312012-10-04 02:19:54 +020014207mainformatlong(PyObject *v,
14208 struct unicode_format_arg_t *arg,
14209 PyObject **p_output,
14210 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014211{
14212 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014213 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014214
14215 if (!PyNumber_Check(v))
14216 goto wrongtype;
14217
Ethan Furman9ab74802014-03-21 06:38:46 -070014218 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014219 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014220 if (type == 'o' || type == 'x' || type == 'X') {
14221 iobj = PyNumber_Index(v);
14222 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014223 if (PyErr_ExceptionMatches(PyExc_TypeError))
14224 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014225 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014226 }
14227 }
14228 else {
14229 iobj = PyNumber_Long(v);
14230 if (iobj == NULL ) {
14231 if (PyErr_ExceptionMatches(PyExc_TypeError))
14232 goto wrongtype;
14233 return -1;
14234 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014235 }
14236 assert(PyLong_Check(iobj));
14237 }
14238 else {
14239 iobj = v;
14240 Py_INCREF(iobj);
14241 }
14242
14243 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014244 && arg->width == -1 && arg->prec == -1
14245 && !(arg->flags & (F_SIGN | F_BLANK))
14246 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014247 {
14248 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014249 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014250 int base;
14251
Victor Stinnera47082312012-10-04 02:19:54 +020014252 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014253 {
14254 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014255 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014256 case 'd':
14257 case 'i':
14258 case 'u':
14259 base = 10;
14260 break;
14261 case 'o':
14262 base = 8;
14263 break;
14264 case 'x':
14265 case 'X':
14266 base = 16;
14267 break;
14268 }
14269
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014270 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14271 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014272 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014273 }
14274 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014275 return 1;
14276 }
14277
Ethan Furmanb95b5612015-01-23 20:05:18 -080014278 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014279 Py_DECREF(iobj);
14280 if (res == NULL)
14281 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014282 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014283 return 0;
14284
14285wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014286 switch(type)
14287 {
14288 case 'o':
14289 case 'x':
14290 case 'X':
14291 PyErr_Format(PyExc_TypeError,
14292 "%%%c format: an integer is required, "
14293 "not %.200s",
14294 type, Py_TYPE(v)->tp_name);
14295 break;
14296 default:
14297 PyErr_Format(PyExc_TypeError,
14298 "%%%c format: a number is required, "
14299 "not %.200s",
14300 type, Py_TYPE(v)->tp_name);
14301 break;
14302 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014303 return -1;
14304}
14305
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014306static Py_UCS4
14307formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014308{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014309 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014310 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014311 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014312 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014313 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014314 goto onError;
14315 }
14316 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014317 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014318 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014319 /* make sure number is a type of integer */
14320 if (!PyLong_Check(v)) {
14321 iobj = PyNumber_Index(v);
14322 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014323 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014324 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014325 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014326 Py_DECREF(iobj);
14327 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014328 else {
14329 x = PyLong_AsLong(v);
14330 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014331 if (x == -1 && PyErr_Occurred())
14332 goto onError;
14333
Victor Stinner8faf8212011-12-08 22:14:11 +010014334 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014335 PyErr_SetString(PyExc_OverflowError,
14336 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014337 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014338 }
14339
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014340 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014341 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014342
Benjamin Peterson29060642009-01-31 22:14:21 +000014343 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014344 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014345 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014346 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014347}
14348
Victor Stinnera47082312012-10-04 02:19:54 +020014349/* Parse options of an argument: flags, width, precision.
14350 Handle also "%(name)" syntax.
14351
14352 Return 0 if the argument has been formatted into arg->str.
14353 Return 1 if the argument has been written into ctx->writer,
14354 Raise an exception and return -1 on error. */
14355static int
14356unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14357 struct unicode_format_arg_t *arg)
14358{
14359#define FORMAT_READ(ctx) \
14360 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14361
14362 PyObject *v;
14363
Victor Stinnera47082312012-10-04 02:19:54 +020014364 if (arg->ch == '(') {
14365 /* Get argument value from a dictionary. Example: "%(name)s". */
14366 Py_ssize_t keystart;
14367 Py_ssize_t keylen;
14368 PyObject *key;
14369 int pcount = 1;
14370
14371 if (ctx->dict == NULL) {
14372 PyErr_SetString(PyExc_TypeError,
14373 "format requires a mapping");
14374 return -1;
14375 }
14376 ++ctx->fmtpos;
14377 --ctx->fmtcnt;
14378 keystart = ctx->fmtpos;
14379 /* Skip over balanced parentheses */
14380 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14381 arg->ch = FORMAT_READ(ctx);
14382 if (arg->ch == ')')
14383 --pcount;
14384 else if (arg->ch == '(')
14385 ++pcount;
14386 ctx->fmtpos++;
14387 }
14388 keylen = ctx->fmtpos - keystart - 1;
14389 if (ctx->fmtcnt < 0 || pcount > 0) {
14390 PyErr_SetString(PyExc_ValueError,
14391 "incomplete format key");
14392 return -1;
14393 }
14394 key = PyUnicode_Substring(ctx->fmtstr,
14395 keystart, keystart + keylen);
14396 if (key == NULL)
14397 return -1;
14398 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014399 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014400 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014401 }
14402 ctx->args = PyObject_GetItem(ctx->dict, key);
14403 Py_DECREF(key);
14404 if (ctx->args == NULL)
14405 return -1;
14406 ctx->args_owned = 1;
14407 ctx->arglen = -1;
14408 ctx->argidx = -2;
14409 }
14410
14411 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014412 while (--ctx->fmtcnt >= 0) {
14413 arg->ch = FORMAT_READ(ctx);
14414 ctx->fmtpos++;
14415 switch (arg->ch) {
14416 case '-': arg->flags |= F_LJUST; continue;
14417 case '+': arg->flags |= F_SIGN; continue;
14418 case ' ': arg->flags |= F_BLANK; continue;
14419 case '#': arg->flags |= F_ALT; continue;
14420 case '0': arg->flags |= F_ZERO; continue;
14421 }
14422 break;
14423 }
14424
14425 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014426 if (arg->ch == '*') {
14427 v = unicode_format_getnextarg(ctx);
14428 if (v == NULL)
14429 return -1;
14430 if (!PyLong_Check(v)) {
14431 PyErr_SetString(PyExc_TypeError,
14432 "* wants int");
14433 return -1;
14434 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014435 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014436 if (arg->width == -1 && PyErr_Occurred())
14437 return -1;
14438 if (arg->width < 0) {
14439 arg->flags |= F_LJUST;
14440 arg->width = -arg->width;
14441 }
14442 if (--ctx->fmtcnt >= 0) {
14443 arg->ch = FORMAT_READ(ctx);
14444 ctx->fmtpos++;
14445 }
14446 }
14447 else if (arg->ch >= '0' && arg->ch <= '9') {
14448 arg->width = arg->ch - '0';
14449 while (--ctx->fmtcnt >= 0) {
14450 arg->ch = FORMAT_READ(ctx);
14451 ctx->fmtpos++;
14452 if (arg->ch < '0' || arg->ch > '9')
14453 break;
14454 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14455 mixing signed and unsigned comparison. Since arg->ch is between
14456 '0' and '9', casting to int is safe. */
14457 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14458 PyErr_SetString(PyExc_ValueError,
14459 "width too big");
14460 return -1;
14461 }
14462 arg->width = arg->width*10 + (arg->ch - '0');
14463 }
14464 }
14465
14466 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014467 if (arg->ch == '.') {
14468 arg->prec = 0;
14469 if (--ctx->fmtcnt >= 0) {
14470 arg->ch = FORMAT_READ(ctx);
14471 ctx->fmtpos++;
14472 }
14473 if (arg->ch == '*') {
14474 v = unicode_format_getnextarg(ctx);
14475 if (v == NULL)
14476 return -1;
14477 if (!PyLong_Check(v)) {
14478 PyErr_SetString(PyExc_TypeError,
14479 "* wants int");
14480 return -1;
14481 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014482 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014483 if (arg->prec == -1 && PyErr_Occurred())
14484 return -1;
14485 if (arg->prec < 0)
14486 arg->prec = 0;
14487 if (--ctx->fmtcnt >= 0) {
14488 arg->ch = FORMAT_READ(ctx);
14489 ctx->fmtpos++;
14490 }
14491 }
14492 else if (arg->ch >= '0' && arg->ch <= '9') {
14493 arg->prec = arg->ch - '0';
14494 while (--ctx->fmtcnt >= 0) {
14495 arg->ch = FORMAT_READ(ctx);
14496 ctx->fmtpos++;
14497 if (arg->ch < '0' || arg->ch > '9')
14498 break;
14499 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14500 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014501 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014502 return -1;
14503 }
14504 arg->prec = arg->prec*10 + (arg->ch - '0');
14505 }
14506 }
14507 }
14508
14509 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14510 if (ctx->fmtcnt >= 0) {
14511 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14512 if (--ctx->fmtcnt >= 0) {
14513 arg->ch = FORMAT_READ(ctx);
14514 ctx->fmtpos++;
14515 }
14516 }
14517 }
14518 if (ctx->fmtcnt < 0) {
14519 PyErr_SetString(PyExc_ValueError,
14520 "incomplete format");
14521 return -1;
14522 }
14523 return 0;
14524
14525#undef FORMAT_READ
14526}
14527
14528/* Format one argument. Supported conversion specifiers:
14529
14530 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014531 - "i", "d", "u": int or float
14532 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014533 - "e", "E", "f", "F", "g", "G": float
14534 - "c": int or str (1 character)
14535
Victor Stinner8dbd4212012-12-04 09:30:24 +010014536 When possible, the output is written directly into the Unicode writer
14537 (ctx->writer). A string is created when padding is required.
14538
Victor Stinnera47082312012-10-04 02:19:54 +020014539 Return 0 if the argument has been formatted into *p_str,
14540 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014541 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014542static int
14543unicode_format_arg_format(struct unicode_formatter_t *ctx,
14544 struct unicode_format_arg_t *arg,
14545 PyObject **p_str)
14546{
14547 PyObject *v;
14548 _PyUnicodeWriter *writer = &ctx->writer;
14549
14550 if (ctx->fmtcnt == 0)
14551 ctx->writer.overallocate = 0;
14552
Victor Stinnera47082312012-10-04 02:19:54 +020014553 v = unicode_format_getnextarg(ctx);
14554 if (v == NULL)
14555 return -1;
14556
Victor Stinnera47082312012-10-04 02:19:54 +020014557
14558 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014559 case 's':
14560 case 'r':
14561 case 'a':
14562 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14563 /* Fast path */
14564 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14565 return -1;
14566 return 1;
14567 }
14568
14569 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14570 *p_str = v;
14571 Py_INCREF(*p_str);
14572 }
14573 else {
14574 if (arg->ch == 's')
14575 *p_str = PyObject_Str(v);
14576 else if (arg->ch == 'r')
14577 *p_str = PyObject_Repr(v);
14578 else
14579 *p_str = PyObject_ASCII(v);
14580 }
14581 break;
14582
14583 case 'i':
14584 case 'd':
14585 case 'u':
14586 case 'o':
14587 case 'x':
14588 case 'X':
14589 {
14590 int ret = mainformatlong(v, arg, p_str, writer);
14591 if (ret != 0)
14592 return ret;
14593 arg->sign = 1;
14594 break;
14595 }
14596
14597 case 'e':
14598 case 'E':
14599 case 'f':
14600 case 'F':
14601 case 'g':
14602 case 'G':
14603 if (arg->width == -1 && arg->prec == -1
14604 && !(arg->flags & (F_SIGN | F_BLANK)))
14605 {
14606 /* Fast path */
14607 if (formatfloat(v, arg, NULL, writer) == -1)
14608 return -1;
14609 return 1;
14610 }
14611
14612 arg->sign = 1;
14613 if (formatfloat(v, arg, p_str, NULL) == -1)
14614 return -1;
14615 break;
14616
14617 case 'c':
14618 {
14619 Py_UCS4 ch = formatchar(v);
14620 if (ch == (Py_UCS4) -1)
14621 return -1;
14622 if (arg->width == -1 && arg->prec == -1) {
14623 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014624 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014625 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014626 return 1;
14627 }
14628 *p_str = PyUnicode_FromOrdinal(ch);
14629 break;
14630 }
14631
14632 default:
14633 PyErr_Format(PyExc_ValueError,
14634 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014635 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014636 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14637 (int)arg->ch,
14638 ctx->fmtpos - 1);
14639 return -1;
14640 }
14641 if (*p_str == NULL)
14642 return -1;
14643 assert (PyUnicode_Check(*p_str));
14644 return 0;
14645}
14646
14647static int
14648unicode_format_arg_output(struct unicode_formatter_t *ctx,
14649 struct unicode_format_arg_t *arg,
14650 PyObject *str)
14651{
14652 Py_ssize_t len;
14653 enum PyUnicode_Kind kind;
14654 void *pbuf;
14655 Py_ssize_t pindex;
14656 Py_UCS4 signchar;
14657 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014658 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014659 Py_ssize_t sublen;
14660 _PyUnicodeWriter *writer = &ctx->writer;
14661 Py_UCS4 fill;
14662
14663 fill = ' ';
14664 if (arg->sign && arg->flags & F_ZERO)
14665 fill = '0';
14666
14667 if (PyUnicode_READY(str) == -1)
14668 return -1;
14669
14670 len = PyUnicode_GET_LENGTH(str);
14671 if ((arg->width == -1 || arg->width <= len)
14672 && (arg->prec == -1 || arg->prec >= len)
14673 && !(arg->flags & (F_SIGN | F_BLANK)))
14674 {
14675 /* Fast path */
14676 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14677 return -1;
14678 return 0;
14679 }
14680
14681 /* Truncate the string for "s", "r" and "a" formats
14682 if the precision is set */
14683 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14684 if (arg->prec >= 0 && len > arg->prec)
14685 len = arg->prec;
14686 }
14687
14688 /* Adjust sign and width */
14689 kind = PyUnicode_KIND(str);
14690 pbuf = PyUnicode_DATA(str);
14691 pindex = 0;
14692 signchar = '\0';
14693 if (arg->sign) {
14694 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14695 if (ch == '-' || ch == '+') {
14696 signchar = ch;
14697 len--;
14698 pindex++;
14699 }
14700 else if (arg->flags & F_SIGN)
14701 signchar = '+';
14702 else if (arg->flags & F_BLANK)
14703 signchar = ' ';
14704 else
14705 arg->sign = 0;
14706 }
14707 if (arg->width < len)
14708 arg->width = len;
14709
14710 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014711 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014712 if (!(arg->flags & F_LJUST)) {
14713 if (arg->sign) {
14714 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014715 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014716 }
14717 else {
14718 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014719 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014720 }
14721 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014722 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14723 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014724 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014725 }
14726
Victor Stinnera47082312012-10-04 02:19:54 +020014727 buflen = arg->width;
14728 if (arg->sign && len == arg->width)
14729 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014730 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014731 return -1;
14732
14733 /* Write the sign if needed */
14734 if (arg->sign) {
14735 if (fill != ' ') {
14736 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14737 writer->pos += 1;
14738 }
14739 if (arg->width > len)
14740 arg->width--;
14741 }
14742
14743 /* Write the numeric prefix for "x", "X" and "o" formats
14744 if the alternate form is used.
14745 For example, write "0x" for the "%#x" format. */
14746 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14747 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14748 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14749 if (fill != ' ') {
14750 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14751 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14752 writer->pos += 2;
14753 pindex += 2;
14754 }
14755 arg->width -= 2;
14756 if (arg->width < 0)
14757 arg->width = 0;
14758 len -= 2;
14759 }
14760
14761 /* Pad left with the fill character if needed */
14762 if (arg->width > len && !(arg->flags & F_LJUST)) {
14763 sublen = arg->width - len;
14764 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14765 writer->pos += sublen;
14766 arg->width = len;
14767 }
14768
14769 /* If padding with spaces: write sign if needed and/or numeric prefix if
14770 the alternate form is used */
14771 if (fill == ' ') {
14772 if (arg->sign) {
14773 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14774 writer->pos += 1;
14775 }
14776 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14777 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14778 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14779 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14780 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14781 writer->pos += 2;
14782 pindex += 2;
14783 }
14784 }
14785
14786 /* Write characters */
14787 if (len) {
14788 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14789 str, pindex, len);
14790 writer->pos += len;
14791 }
14792
14793 /* Pad right with the fill character if needed */
14794 if (arg->width > len) {
14795 sublen = arg->width - len;
14796 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14797 writer->pos += sublen;
14798 }
14799 return 0;
14800}
14801
14802/* Helper of PyUnicode_Format(): format one arg.
14803 Return 0 on success, raise an exception and return -1 on error. */
14804static int
14805unicode_format_arg(struct unicode_formatter_t *ctx)
14806{
14807 struct unicode_format_arg_t arg;
14808 PyObject *str;
14809 int ret;
14810
Victor Stinner8dbd4212012-12-04 09:30:24 +010014811 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014812 if (arg.ch == '%') {
14813 ctx->fmtpos++;
14814 ctx->fmtcnt--;
14815 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14816 return -1;
14817 return 0;
14818 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014819 arg.flags = 0;
14820 arg.width = -1;
14821 arg.prec = -1;
14822 arg.sign = 0;
14823 str = NULL;
14824
Victor Stinnera47082312012-10-04 02:19:54 +020014825 ret = unicode_format_arg_parse(ctx, &arg);
14826 if (ret == -1)
14827 return -1;
14828
14829 ret = unicode_format_arg_format(ctx, &arg, &str);
14830 if (ret == -1)
14831 return -1;
14832
14833 if (ret != 1) {
14834 ret = unicode_format_arg_output(ctx, &arg, str);
14835 Py_DECREF(str);
14836 if (ret == -1)
14837 return -1;
14838 }
14839
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014840 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014841 PyErr_SetString(PyExc_TypeError,
14842 "not all arguments converted during string formatting");
14843 return -1;
14844 }
14845 return 0;
14846}
14847
Alexander Belopolsky40018472011-02-26 01:02:56 +000014848PyObject *
14849PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014850{
Victor Stinnera47082312012-10-04 02:19:54 +020014851 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014852
Guido van Rossumd57fd912000-03-10 22:53:23 +000014853 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014854 PyErr_BadInternalCall();
14855 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014856 }
Victor Stinnera47082312012-10-04 02:19:54 +020014857
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014858 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014859 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014860
14861 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014862 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14863 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14864 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14865 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014866
Victor Stinner8f674cc2013-04-17 23:02:17 +020014867 _PyUnicodeWriter_Init(&ctx.writer);
14868 ctx.writer.min_length = ctx.fmtcnt + 100;
14869 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014870
Guido van Rossumd57fd912000-03-10 22:53:23 +000014871 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014872 ctx.arglen = PyTuple_Size(args);
14873 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014874 }
14875 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014876 ctx.arglen = -1;
14877 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014878 }
Victor Stinnera47082312012-10-04 02:19:54 +020014879 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014880 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014881 ctx.dict = args;
14882 else
14883 ctx.dict = NULL;
14884 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014885
Victor Stinnera47082312012-10-04 02:19:54 +020014886 while (--ctx.fmtcnt >= 0) {
14887 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014888 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014889
14890 nonfmtpos = ctx.fmtpos++;
14891 while (ctx.fmtcnt >= 0 &&
14892 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14893 ctx.fmtpos++;
14894 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014895 }
Victor Stinnera47082312012-10-04 02:19:54 +020014896 if (ctx.fmtcnt < 0) {
14897 ctx.fmtpos--;
14898 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014899 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014900
Victor Stinnercfc4c132013-04-03 01:48:39 +020014901 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14902 nonfmtpos, ctx.fmtpos) < 0)
14903 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014904 }
14905 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014906 ctx.fmtpos++;
14907 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014908 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014909 }
14910 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014911
Victor Stinnera47082312012-10-04 02:19:54 +020014912 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014913 PyErr_SetString(PyExc_TypeError,
14914 "not all arguments converted during string formatting");
14915 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014916 }
14917
Victor Stinnera47082312012-10-04 02:19:54 +020014918 if (ctx.args_owned) {
14919 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014920 }
Victor Stinnera47082312012-10-04 02:19:54 +020014921 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014922
Benjamin Peterson29060642009-01-31 22:14:21 +000014923 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014924 _PyUnicodeWriter_Dealloc(&ctx.writer);
14925 if (ctx.args_owned) {
14926 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014927 }
14928 return NULL;
14929}
14930
Jeremy Hylton938ace62002-07-17 16:30:39 +000014931static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014932unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14933
Tim Peters6d6c1a32001-08-02 04:15:00 +000014934static PyObject *
14935unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14936{
Benjamin Peterson29060642009-01-31 22:14:21 +000014937 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014938 static char *kwlist[] = {"object", "encoding", "errors", 0};
14939 char *encoding = NULL;
14940 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014941
Benjamin Peterson14339b62009-01-31 16:36:08 +000014942 if (type != &PyUnicode_Type)
14943 return unicode_subtype_new(type, args, kwds);
14944 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014945 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014946 return NULL;
14947 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014948 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014949 if (encoding == NULL && errors == NULL)
14950 return PyObject_Str(x);
14951 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014952 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014953}
14954
Guido van Rossume023fe02001-08-30 03:12:59 +000014955static PyObject *
14956unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14957{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014958 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014959 Py_ssize_t length, char_size;
14960 int share_wstr, share_utf8;
14961 unsigned int kind;
14962 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014963
Benjamin Peterson14339b62009-01-31 16:36:08 +000014964 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014965
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014966 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014967 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014968 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014969 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014970 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014971 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014972 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014973 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014974
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014975 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014976 if (self == NULL) {
14977 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014978 return NULL;
14979 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014980 kind = PyUnicode_KIND(unicode);
14981 length = PyUnicode_GET_LENGTH(unicode);
14982
14983 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014984#ifdef Py_DEBUG
14985 _PyUnicode_HASH(self) = -1;
14986#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014987 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014988#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014989 _PyUnicode_STATE(self).interned = 0;
14990 _PyUnicode_STATE(self).kind = kind;
14991 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014992 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014993 _PyUnicode_STATE(self).ready = 1;
14994 _PyUnicode_WSTR(self) = NULL;
14995 _PyUnicode_UTF8_LENGTH(self) = 0;
14996 _PyUnicode_UTF8(self) = NULL;
14997 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014998 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014999
15000 share_utf8 = 0;
15001 share_wstr = 0;
15002 if (kind == PyUnicode_1BYTE_KIND) {
15003 char_size = 1;
15004 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15005 share_utf8 = 1;
15006 }
15007 else if (kind == PyUnicode_2BYTE_KIND) {
15008 char_size = 2;
15009 if (sizeof(wchar_t) == 2)
15010 share_wstr = 1;
15011 }
15012 else {
15013 assert(kind == PyUnicode_4BYTE_KIND);
15014 char_size = 4;
15015 if (sizeof(wchar_t) == 4)
15016 share_wstr = 1;
15017 }
15018
15019 /* Ensure we won't overflow the length. */
15020 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15021 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015022 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015023 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015024 data = PyObject_MALLOC((length + 1) * char_size);
15025 if (data == NULL) {
15026 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015027 goto onError;
15028 }
15029
Victor Stinnerc3c74152011-10-02 20:39:55 +020015030 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015031 if (share_utf8) {
15032 _PyUnicode_UTF8_LENGTH(self) = length;
15033 _PyUnicode_UTF8(self) = data;
15034 }
15035 if (share_wstr) {
15036 _PyUnicode_WSTR_LENGTH(self) = length;
15037 _PyUnicode_WSTR(self) = (wchar_t *)data;
15038 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015039
Christian Heimesf051e432016-09-13 20:22:02 +020015040 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015041 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015042 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015043#ifdef Py_DEBUG
15044 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15045#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015046 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015047 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015048
15049onError:
15050 Py_DECREF(unicode);
15051 Py_DECREF(self);
15052 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015053}
15054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015055PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015056"str(object='') -> str\n\
15057str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015058\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015059Create a new string object from the given object. If encoding or\n\
15060errors is specified, then the object must expose a data buffer\n\
15061that will be decoded using the given encoding and error handler.\n\
15062Otherwise, returns the result of object.__str__() (if defined)\n\
15063or repr(object).\n\
15064encoding defaults to sys.getdefaultencoding().\n\
15065errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015066
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015067static PyObject *unicode_iter(PyObject *seq);
15068
Guido van Rossumd57fd912000-03-10 22:53:23 +000015069PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015070 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015071 "str", /* tp_name */
15072 sizeof(PyUnicodeObject), /* tp_basicsize */
15073 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015074 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015075 (destructor)unicode_dealloc, /* tp_dealloc */
15076 0, /* tp_print */
15077 0, /* tp_getattr */
15078 0, /* tp_setattr */
15079 0, /* tp_reserved */
15080 unicode_repr, /* tp_repr */
15081 &unicode_as_number, /* tp_as_number */
15082 &unicode_as_sequence, /* tp_as_sequence */
15083 &unicode_as_mapping, /* tp_as_mapping */
15084 (hashfunc) unicode_hash, /* tp_hash*/
15085 0, /* tp_call*/
15086 (reprfunc) unicode_str, /* tp_str */
15087 PyObject_GenericGetAttr, /* tp_getattro */
15088 0, /* tp_setattro */
15089 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015090 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015091 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15092 unicode_doc, /* tp_doc */
15093 0, /* tp_traverse */
15094 0, /* tp_clear */
15095 PyUnicode_RichCompare, /* tp_richcompare */
15096 0, /* tp_weaklistoffset */
15097 unicode_iter, /* tp_iter */
15098 0, /* tp_iternext */
15099 unicode_methods, /* tp_methods */
15100 0, /* tp_members */
15101 0, /* tp_getset */
15102 &PyBaseObject_Type, /* tp_base */
15103 0, /* tp_dict */
15104 0, /* tp_descr_get */
15105 0, /* tp_descr_set */
15106 0, /* tp_dictoffset */
15107 0, /* tp_init */
15108 0, /* tp_alloc */
15109 unicode_new, /* tp_new */
15110 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015111};
15112
15113/* Initialize the Unicode implementation */
15114
Victor Stinner3a50e702011-10-18 21:21:00 +020015115int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015116{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015117 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015118 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015119 0x000A, /* LINE FEED */
15120 0x000D, /* CARRIAGE RETURN */
15121 0x001C, /* FILE SEPARATOR */
15122 0x001D, /* GROUP SEPARATOR */
15123 0x001E, /* RECORD SEPARATOR */
15124 0x0085, /* NEXT LINE */
15125 0x2028, /* LINE SEPARATOR */
15126 0x2029, /* PARAGRAPH SEPARATOR */
15127 };
15128
Fred Drakee4315f52000-05-09 19:53:39 +000015129 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015130 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015131 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015132 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015133 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015134
Guido van Rossumcacfc072002-05-24 19:01:59 +000015135 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015136 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015137
15138 /* initialize the linebreak bloom filter */
15139 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015140 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015141 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015142
Christian Heimes26532f72013-07-20 14:57:16 +020015143 if (PyType_Ready(&EncodingMapType) < 0)
15144 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015145
Benjamin Petersonc4311282012-10-30 23:21:10 -040015146 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15147 Py_FatalError("Can't initialize field name iterator type");
15148
15149 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15150 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015151
Victor Stinner3a50e702011-10-18 21:21:00 +020015152 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015153}
15154
15155/* Finalize the Unicode implementation */
15156
Christian Heimesa156e092008-02-16 07:38:31 +000015157int
15158PyUnicode_ClearFreeList(void)
15159{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015160 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015161}
15162
Guido van Rossumd57fd912000-03-10 22:53:23 +000015163void
Thomas Wouters78890102000-07-22 19:25:51 +000015164_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015165{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015166 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015167
Serhiy Storchaka05997252013-01-26 12:14:02 +020015168 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015169
Serhiy Storchaka05997252013-01-26 12:14:02 +020015170 for (i = 0; i < 256; i++)
15171 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015172 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015173 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015174}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015175
Walter Dörwald16807132007-05-25 13:52:07 +000015176void
15177PyUnicode_InternInPlace(PyObject **p)
15178{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015179 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015180 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015181#ifdef Py_DEBUG
15182 assert(s != NULL);
15183 assert(_PyUnicode_CHECK(s));
15184#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015185 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015186 return;
15187#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015188 /* If it's a subclass, we don't really know what putting
15189 it in the interned dict might do. */
15190 if (!PyUnicode_CheckExact(s))
15191 return;
15192 if (PyUnicode_CHECK_INTERNED(s))
15193 return;
15194 if (interned == NULL) {
15195 interned = PyDict_New();
15196 if (interned == NULL) {
15197 PyErr_Clear(); /* Don't leave an exception */
15198 return;
15199 }
15200 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015201 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015202 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015203 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015204 if (t == NULL) {
15205 PyErr_Clear();
15206 return;
15207 }
15208 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015209 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015210 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015211 return;
15212 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015213 /* The two references in interned are not counted by refcnt.
15214 The deallocator will take care of this */
15215 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015216 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015217}
15218
15219void
15220PyUnicode_InternImmortal(PyObject **p)
15221{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015222 PyUnicode_InternInPlace(p);
15223 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015224 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015225 Py_INCREF(*p);
15226 }
Walter Dörwald16807132007-05-25 13:52:07 +000015227}
15228
15229PyObject *
15230PyUnicode_InternFromString(const char *cp)
15231{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015232 PyObject *s = PyUnicode_FromString(cp);
15233 if (s == NULL)
15234 return NULL;
15235 PyUnicode_InternInPlace(&s);
15236 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015237}
15238
Alexander Belopolsky40018472011-02-26 01:02:56 +000015239void
15240_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015241{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015242 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015243 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015244 Py_ssize_t i, n;
15245 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015246
Benjamin Peterson14339b62009-01-31 16:36:08 +000015247 if (interned == NULL || !PyDict_Check(interned))
15248 return;
15249 keys = PyDict_Keys(interned);
15250 if (keys == NULL || !PyList_Check(keys)) {
15251 PyErr_Clear();
15252 return;
15253 }
Walter Dörwald16807132007-05-25 13:52:07 +000015254
Benjamin Peterson14339b62009-01-31 16:36:08 +000015255 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15256 detector, interned unicode strings are not forcibly deallocated;
15257 rather, we give them their stolen references back, and then clear
15258 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015259
Benjamin Peterson14339b62009-01-31 16:36:08 +000015260 n = PyList_GET_SIZE(keys);
15261 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015262 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015263 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015264 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015265 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015266 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015268 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015269 case SSTATE_NOT_INTERNED:
15270 /* XXX Shouldn't happen */
15271 break;
15272 case SSTATE_INTERNED_IMMORTAL:
15273 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015274 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015275 break;
15276 case SSTATE_INTERNED_MORTAL:
15277 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015278 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015279 break;
15280 default:
15281 Py_FatalError("Inconsistent interned string state.");
15282 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015283 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015284 }
15285 fprintf(stderr, "total size of all interned strings: "
15286 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15287 "mortal/immortal\n", mortal_size, immortal_size);
15288 Py_DECREF(keys);
15289 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015290 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015291}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015292
15293
15294/********************* Unicode Iterator **************************/
15295
15296typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015297 PyObject_HEAD
15298 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015299 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015300} unicodeiterobject;
15301
15302static void
15303unicodeiter_dealloc(unicodeiterobject *it)
15304{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015305 _PyObject_GC_UNTRACK(it);
15306 Py_XDECREF(it->it_seq);
15307 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015308}
15309
15310static int
15311unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15312{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015313 Py_VISIT(it->it_seq);
15314 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015315}
15316
15317static PyObject *
15318unicodeiter_next(unicodeiterobject *it)
15319{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015320 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015321
Benjamin Peterson14339b62009-01-31 16:36:08 +000015322 assert(it != NULL);
15323 seq = it->it_seq;
15324 if (seq == NULL)
15325 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015326 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015328 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15329 int kind = PyUnicode_KIND(seq);
15330 void *data = PyUnicode_DATA(seq);
15331 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15332 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015333 if (item != NULL)
15334 ++it->it_index;
15335 return item;
15336 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015337
Benjamin Peterson14339b62009-01-31 16:36:08 +000015338 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015339 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015340 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015341}
15342
15343static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015344unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015345{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015346 Py_ssize_t len = 0;
15347 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015348 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015349 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015350}
15351
15352PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15353
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015354static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015355unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015356{
15357 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015358 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015359 it->it_seq, it->it_index);
15360 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015361 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015362 if (u == NULL)
15363 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015364 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015365 }
15366}
15367
15368PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15369
15370static PyObject *
15371unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15372{
15373 Py_ssize_t index = PyLong_AsSsize_t(state);
15374 if (index == -1 && PyErr_Occurred())
15375 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015376 if (it->it_seq != NULL) {
15377 if (index < 0)
15378 index = 0;
15379 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15380 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15381 it->it_index = index;
15382 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015383 Py_RETURN_NONE;
15384}
15385
15386PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15387
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015388static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015389 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015390 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015391 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15392 reduce_doc},
15393 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15394 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015395 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015396};
15397
15398PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015399 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15400 "str_iterator", /* tp_name */
15401 sizeof(unicodeiterobject), /* tp_basicsize */
15402 0, /* tp_itemsize */
15403 /* methods */
15404 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15405 0, /* tp_print */
15406 0, /* tp_getattr */
15407 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015408 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015409 0, /* tp_repr */
15410 0, /* tp_as_number */
15411 0, /* tp_as_sequence */
15412 0, /* tp_as_mapping */
15413 0, /* tp_hash */
15414 0, /* tp_call */
15415 0, /* tp_str */
15416 PyObject_GenericGetAttr, /* tp_getattro */
15417 0, /* tp_setattro */
15418 0, /* tp_as_buffer */
15419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15420 0, /* tp_doc */
15421 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15422 0, /* tp_clear */
15423 0, /* tp_richcompare */
15424 0, /* tp_weaklistoffset */
15425 PyObject_SelfIter, /* tp_iter */
15426 (iternextfunc)unicodeiter_next, /* tp_iternext */
15427 unicodeiter_methods, /* tp_methods */
15428 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015429};
15430
15431static PyObject *
15432unicode_iter(PyObject *seq)
15433{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015434 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015435
Benjamin Peterson14339b62009-01-31 16:36:08 +000015436 if (!PyUnicode_Check(seq)) {
15437 PyErr_BadInternalCall();
15438 return NULL;
15439 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015440 if (PyUnicode_READY(seq) == -1)
15441 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015442 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15443 if (it == NULL)
15444 return NULL;
15445 it->it_index = 0;
15446 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015447 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015448 _PyObject_GC_TRACK(it);
15449 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015450}
15451
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015452
15453size_t
15454Py_UNICODE_strlen(const Py_UNICODE *u)
15455{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015456 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015457}
15458
15459Py_UNICODE*
15460Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15461{
15462 Py_UNICODE *u = s1;
15463 while ((*u++ = *s2++));
15464 return s1;
15465}
15466
15467Py_UNICODE*
15468Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15469{
15470 Py_UNICODE *u = s1;
15471 while ((*u++ = *s2++))
15472 if (n-- == 0)
15473 break;
15474 return s1;
15475}
15476
15477Py_UNICODE*
15478Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15479{
15480 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015481 u1 += wcslen(u1);
15482 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015483 return s1;
15484}
15485
15486int
15487Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15488{
15489 while (*s1 && *s2 && *s1 == *s2)
15490 s1++, s2++;
15491 if (*s1 && *s2)
15492 return (*s1 < *s2) ? -1 : +1;
15493 if (*s1)
15494 return 1;
15495 if (*s2)
15496 return -1;
15497 return 0;
15498}
15499
15500int
15501Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15502{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015503 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015504 for (; n != 0; n--) {
15505 u1 = *s1;
15506 u2 = *s2;
15507 if (u1 != u2)
15508 return (u1 < u2) ? -1 : +1;
15509 if (u1 == '\0')
15510 return 0;
15511 s1++;
15512 s2++;
15513 }
15514 return 0;
15515}
15516
15517Py_UNICODE*
15518Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15519{
15520 const Py_UNICODE *p;
15521 for (p = s; *p; p++)
15522 if (*p == c)
15523 return (Py_UNICODE*)p;
15524 return NULL;
15525}
15526
15527Py_UNICODE*
15528Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15529{
15530 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015531 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015532 while (p != s) {
15533 p--;
15534 if (*p == c)
15535 return (Py_UNICODE*)p;
15536 }
15537 return NULL;
15538}
Victor Stinner331ea922010-08-10 16:37:20 +000015539
Victor Stinner71133ff2010-09-01 23:43:53 +000015540Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015541PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015542{
Victor Stinner577db2c2011-10-11 22:12:48 +020015543 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015544 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015546 if (!PyUnicode_Check(unicode)) {
15547 PyErr_BadArgument();
15548 return NULL;
15549 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015550 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015551 if (u == NULL)
15552 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015553 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015554 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015555 PyErr_NoMemory();
15556 return NULL;
15557 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015558 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015559 size *= sizeof(Py_UNICODE);
15560 copy = PyMem_Malloc(size);
15561 if (copy == NULL) {
15562 PyErr_NoMemory();
15563 return NULL;
15564 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015565 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015566 return copy;
15567}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015568
Georg Brandl66c221e2010-10-14 07:04:07 +000015569/* A _string module, to export formatter_parser and formatter_field_name_split
15570 to the string.Formatter class implemented in Python. */
15571
15572static PyMethodDef _string_methods[] = {
15573 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15574 METH_O, PyDoc_STR("split the argument as a field name")},
15575 {"formatter_parser", (PyCFunction) formatter_parser,
15576 METH_O, PyDoc_STR("parse the argument as a format string")},
15577 {NULL, NULL}
15578};
15579
15580static struct PyModuleDef _string_module = {
15581 PyModuleDef_HEAD_INIT,
15582 "_string",
15583 PyDoc_STR("string helper module"),
15584 0,
15585 _string_methods,
15586 NULL,
15587 NULL,
15588 NULL,
15589 NULL
15590};
15591
15592PyMODINIT_FUNC
15593PyInit__string(void)
15594{
15595 return PyModule_Create(&_string_module);
15596}
15597
15598
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015599#ifdef __cplusplus
15600}
15601#endif